// Additive primes: primes whose sum of digits is also prime
public class AdditivePrimes {
// Check if a number is prime
static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int i = 5; i * i <= n; i += 4) {
if (n % i == 0)
return false;
i += 2;
if (n % i == 0)
return false;
}
return true;
}
// Compute the sum of digits of a number
static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
// Check if a number is an additive prime
static boolean isAdditivePrime(int n) {
return isPrime(n) && isPrime(sumDigits(n));
}
public static void main(String[] args) {
final int TOP = 500;
int count = 0;
for (int i = 1; i < TOP; i++) {
if (isAdditivePrime(i)) {
System.out.printf("%3d", i);
count++;
if (count % 10 == 0)
System.out.println();
else
System.out.print(" ");
}
}
System.out.println();
System.out.println();
System.out.println("Total additive primes = " + count);
}
}
/*
run:
2 3 5 7 11 23 29 41 43 47
61 67 83 89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487
Total additive primes = 54
*/