Hackerrank Challenge - Find the highest Prime Number
Consider a positive number innum. Identify and print the number outnum based on the below logic
- Find all the possible sub sequences without leading 0’s of the innum which form prime numbers
- Subsequence: A subsequence of a number num is the possible set of digits formed from num starting from left to right
- Assign the highest identified subsequence to outnum
- If there exists no such subsequence print -1.
Note: 0 and 1 are not prime numbers
Input Format
Read the innum from the standard input stream.
Constraints
1<=n<=10^6
Output Format
Print the outnum to the standard output stream.
Sample Input 0
50678
Sample Output 0
67
Explanation 0
For the given innum i.e. 50678 the sub sequences without leading 0’s formed are 5, 50, 506,5067, 50678, 5068, 507, 5078, 508, 56, 567, 5678, 568, 57,578, 58, 6, 67, 678, 68, 7, 78 and 8. Among these 5, 7 and 67 are prime numbers. Hence 67 is the highest prime number. Hence the output.
Sample Input 1
140
Sample Output 1
-1
Explanation 1
For the given innum, i.e. 140 the subsequence formed are 1, 14, 140, 10, 4, 40 and 0. None of the sub sequences are prime numbers. Hence the output is -1
Code
import java.io.*;
import java.math.BigInteger;
import java.util.*;
class Result {
// Set to store all subsequences
static HashSet<String> st = new HashSet<>();
// Function to compute all the subsequences of a string
static void subsequence(String str){
// Iterate over the entire string
for (int i = 0; i < str.length(); i++) {
// Iterate from the end of the string
// to generate substrings
for (int j = str.length(); j > i; j--) {
String sub_str = str.substring(i,j);
if(!st.contains(sub_str) && !sub_str.startsWith("0")){
st.add(sub_str);
}
// Drop the kth character in the substring
// and if its not in the set then recur
for (int k = 0; k < sub_str.length()-1; k++) {
StringBuffer sb = new StringBuffer(sub_str);
// Drop characters from the string
sb.deleteCharAt(k);
if(!st.contains(sb.toString()) && !sb.toString().startsWith("0")){
st.add(sb.toString());
}
subsequence(sb.toString());
}
}
}
}
private static ArrayList<BigInteger> getPrime() {
Object[] tempArray = st.toArray();
ArrayList<BigInteger> primeList = new ArrayList<BigInteger>();
// For Loop
for (int i = 0; i < tempArray.length; i++) {
BigInteger num = BigInteger.valueOf(Integer.parseInt((String) tempArray[i]));
if(num.isProbablePrime(1)){
primeList.add(num);
}
}
return primeList;
}
public static void maximumPrime(int n) {
String s = n+"";
subsequence(s);
ArrayList<BigInteger> primeList = getPrime();
try {
System.out.println(Collections.max(primeList));
}catch (Exception e){
System.out.println(-1);
}
}
}
class Solution {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Result.maximumPrime(n);
}
}
Comments
Post a Comment