Finding Nth Additive Prime [Java] | LazyLab
A positive integer is called an additive prime number if it is prime and the sum of its digits is also prime.
For example, 83 is prime, and 8 + 3 = 11, which is also prime. Thus, 83 is an additive prime. Note that all single digit primes sum to themselves, and are thus additive primes.
Your task is to calculate elements in the sequence of additive primes.
Input Format:
Given an integer N.
Output Format:
Print the Nth additive prime.
Sample Input00:
1
Sample Output00:
2
Sample Input01:
2
Sample Output01:
3
Sample Input02:
9
Sample Output02:
43
Constraints:
1 <= N <= 200,000
A positive integer is called an additive prime number if it is prime and the sum of its digits is also prime.
For example, 83 is prime, and 8 + 3 = 11, which is also prime. Thus, 83 is an additive prime. Note that all single digit primes sum to themselves, and are thus additive primes.
Your task is to calculate elements in the sequence of additive primes.
Input Format:
Given an integer N.
Output Format:
Print the Nth additive prime.
Sample Input00:
1
Sample Output00:
2
Sample Input01:
2
Sample Output01:
3
Sample Input02:
9
Sample Output02:
43
Constraints:
1 <= N <= 200,000
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.nextLine()); int S =N*50; boolean[] isPrime = new boolean[S]; int l = 0; int number = 2; for(int i=2;i<S;i++){ isPrime[i]=true; } for (int i = 2; i < S; i++) { if(isPrime[i]){ for(int j=2;j<S/i;j++){ isPrime[i*j]=false; } int x = totalOfDigits(i); if (isPrime[x]) { l++; } } if (l == N) { number = i; break; } } System.out.println(number); } private static int totalOfDigits(int i) { int total = 0; while (i / 10 != 0) { total = total + i % 10; i = i / 10; } total = total + i; return total; }Read full article from Finding Nth Additive Prime [Java] | LazyLab