Problem:
The smallest positive integer n for which the numbers n2+1, n2+3, n2+7, n2+9, n2+13, and n2+27 are consecutive primes is 10. The sum of all such integers n below one-million is 1242490.
What is the sum of all such integers n below 150 million?
What is the sum of all such integers n below 150 million?
Solution:
5777
Code:
The solution may include methods that will be found here: Library.java .
public interface EulerSolution{
public String run();
}
/*
* Solution to Project Euler problem 46
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p046 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p046().run());
}
public String run() {
for (int i = 2; ; i++) {
if (!satisfiesConjecture(i))
return Integer.toString(i);
}
}
private boolean satisfiesConjecture(int n) {
if (n % 2 == 0 || isPrime(n))
return true;
// Now n is an odd composite number
for (int i = 1; i * i * 2 <= n; i++) {
if (isPrime(n - i * i * 2))
return true;
}
return false;
}
private boolean[] isPrime = {};
private boolean isPrime(int n) {
if (n >= isPrime.length)
isPrime = Library.listPrimality(n * 2);
return isPrime[n];
}
}
No comments :
Post a Comment