Files
ProjectEulerJava/Problem27.java

82 lines
2.9 KiB
Java

//ProjectEuler/Java/Problem27.java
//Matthew Ellison
// Created: 09-15-19
//Modified: 09-15-19
//Find the product of the coefficients, |a| < 1000 and |b| <= 1000, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0.
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
Copyright (C) 2019 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import mattrixwv.Stopwatch;
import mattrixwv.Algorithms;
import java.util.ArrayList;
public class Problem27{
private static Integer topA = 0; //The A for the most n's generated
private static Integer topB = 0; //The B for the most n's generated
private static Integer topN = 0; //The most n's generated
private static ArrayList<Integer> primes = Algorithms.getPrimes(12000); //A list of all primes that could possibly be generated with this formula
public static void main(String[] args){
//Setup the variables
Stopwatch timer = new Stopwatch();
//Start the timer
timer.start();
//Start with the lowest possible A and check all possibilities after that
for(Integer a = -999;a <= 999;++a){
//Start with the lowest possible B and check all possibilities after that
for(Integer b = -1000;b <=1000;++b){
//Start with n=0 and check the formula to see how many primes you can get get with concecutive n's
Integer n = 0;
Integer quadratic = (n * n) + (a * n) + b;
while(Algorithms.isFound(primes, quadratic)){
++n;
quadratic = (n * n) + (a * n) + b;
}
--n; //Negate an n because the last formula failed
//Set all the largest numbers if this created more primes than any other
if(n > topN){
topN = n;
topB = b;
topA = a;
}
}
}
//Stop the timer
timer.stop();
//Print the restuls
System.out.printf("The greatest number of primes found is %d", topN);
System.out.printf("\nIt was found with A = %d, B = %d", topA, topB);
System.out.printf("\nThe product of A and B is %d\n", topA * topB);
System.out.println("It took " + timer.getStr() + " to run this algorithm");
}
}
/* Results:
The greatest number of primes found is 70
It was found with A = -61, B = 971
The product of A and B is -59231
It took 4.765 seconds to run this algorithm
*/