-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProblem_037.java
More file actions
50 lines (41 loc) · 1.17 KB
/
Problem_037.java
File metadata and controls
50 lines (41 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package euler;
import java.util.ArrayList;
public class Problem_037 {
static long truncatablePrimeSum() {
long sum = 0;
long possiblePrime = 11;
ArrayList<Long> truncatablePrimes = new ArrayList<Long>(11);
while(truncatablePrimes.size() < 11) {
if(isPrime(possiblePrime) && isTruncatableFromRight(possiblePrime) && isTruncatableFromLeft(possiblePrime)) {
truncatablePrimes.add(possiblePrime);
sum += possiblePrime;
}
possiblePrime += 2;
}
// System.out.println(truncatablePrimes.toString());
return sum;
}
private static boolean isTruncatableFromLeft(long num) {
while(num > 0) {
num /= 10;
if(num != 0 && ! isPrime(num)) return false;
}
return true;
}
private static boolean isTruncatableFromRight(long num) {
int power = (int) Math.log10(num);
while(power > 0) {
if(! isPrime(num % (int) Math.pow(10, power))) return false;
power--;
}
return true;
}
private static boolean isPrime(long num) {
if (num < 2) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (long i = 3; i * i <= num; i += 2)
if (num % i == 0) return false;
return true;
}
}