Problem specification: ProjectEuler.net Problem 27
Considering quadratics of the form:
n^2 + an + b, where |a| < 1000 and |b| < 1000
where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |-4| = 4
Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.
Execution time: 390ms (laptop)
CODE
package projecteuler;
import java.util.ArrayList;
/**
* Project euler problem 27 java solution
* @author Mike
*/
public class Problem_27 {
private int aa;
private int bb;
private int[] primes;
private int num;
public static void main(String[] args){
new Problem_27();
}
public Problem_27(){
long start = System.currentTimeMillis();
aa = 0;
bb = 0;
num = 0;
primes = new int[100000];
for(int i = 2; i < 99999; i++){
primes[i] = i;
}
for(int i = 2; i < 50000; i++){
if(primes[i] != 0){
for(int j = 2 * i; j < 50000; j+=i){
primes[j] = 0;
}
}
}
// now we have our thingy...
boolean cont = true;
for(int a = -1000; a <= 1000; a++){
for(int b = -1000; b <= 1000 && cont; b++){
for(int n = 0; n < 600 && cont; n++){
double res = Math.pow(n, 2) + (a * n) + b;
int result = (int) res;
if(result > 0){
if(primes[result] == 0){
cont = false;
} else {
if(n > num){
num = n;
aa= a;
bb = b;
}
}
} else {
cont = false;
}
}
cont = true;
}
cont = true;
}
System.out.println("b = " + bb + " a = " + aa + " with total " + num);
long end = System.currentTimeMillis();
System.out.println(end - start + " ms");
}
}
Any suggestions and comments are welcome, please send me an email (see contacts).