Files
ProjectEulerPython/Problem27.py

72 lines
2.6 KiB
Python

#ProjectEuler/Python/Problem27.py
#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 of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
"""
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/>.
"""
from Stopwatch import Stopwatch
import Algorithms
def Problem27():
#Setup the variables
topA = 0 #The A for the most n's generated
topB = 0 #The B for the most n's generated
topN = 0 #The most n's generated
primes = Algorithms.getPrimes(12000) #A list of all primes that could possibly be generated with this formula
#Start with the lowest possible A and check all possibilities after that
for a in range(-999, 999):
#Start with the lowest possible B and check all possibilities after that
for b in range(-1000, 1000):
#Start with n=0 and check the formula to see how many primes you can get get with concecutive n's
n = 0
quadratic = (n * n) + (a * n) + b
while(quadratic in primes):
n += 1
quadratic = (n * n) + (a * n) + b
n -= 1 #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
print("The greatest number of primes found is " + str(topN))
print("It was found with A = " + str(topA) + ", B = " + str(topB))
print("The product of A and B is " + str(topA * topB))
#This calls the appropriate functions if the script is called stand alone
if __name__ == "__main__":
timer = Stopwatch()
timer.start()
Problem27()
timer.stop()
print("It took " + timer.getString() + " 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 35.775 seconds to run this algorithm
"""