Rebased projecteuler folder, now includes all contest programming stuff
This commit is contained in:
69
projecteuler/027/main.py
Normal file
69
projecteuler/027/main.py
Normal file
@@ -0,0 +1,69 @@
|
||||
# Quadratic primes
|
||||
|
||||
# Consider quadratics of the form:
|
||||
# n^2 + an + b, where abs(a) < 1000 and abs(b) <= 1000
|
||||
|
||||
# Find the product of the coefficients, a * b, for the quadratic expression that
|
||||
# produces the maximum number of primes for consecutive values of n, starting from n = 0
|
||||
|
||||
import numpy as np
|
||||
import math
|
||||
|
||||
def quad(a, b, n):
|
||||
return n**2 + a * n + b
|
||||
|
||||
# Thing that immediately stands out is that b always needs to be prime itself,
|
||||
# since for n=0 only b remains, so that thins the pool a lot
|
||||
# So get the prime thingy out again
|
||||
|
||||
def getPrimes(n):
|
||||
primes = [1 for p in range(n)]
|
||||
primes[0] = 0
|
||||
primes[1] = 0
|
||||
|
||||
x = 2
|
||||
while x < np.sqrt(n):
|
||||
if primes[x] == 1:
|
||||
|
||||
for i in range(x+x, n, x):
|
||||
primes[i] = 0
|
||||
|
||||
x += 1
|
||||
|
||||
result = []
|
||||
for i in range(n):
|
||||
if primes[i]:
|
||||
result.append(i)
|
||||
|
||||
return result
|
||||
|
||||
def getPrimeSequenceLength(a, b, primes):
|
||||
n = 0
|
||||
while True:
|
||||
if quad(a, b, n) in primes:
|
||||
n += 1
|
||||
else:
|
||||
break
|
||||
|
||||
return n - 1
|
||||
|
||||
def main():
|
||||
print("Hello, this is Patrick")
|
||||
|
||||
ps = getPrimes(1000000)
|
||||
littleps = list(filter(lambda p: p < 1000, ps))
|
||||
|
||||
maxprod = 0
|
||||
maxlength = 0
|
||||
for b in littleps:
|
||||
for a in range(-b, 1000):
|
||||
psl = getPrimeSequenceLength(a, b, ps)
|
||||
if psl > maxlength:
|
||||
maxlength = psl
|
||||
maxprod = a * b
|
||||
|
||||
print(f"The maximum prime sequence {maxlength} was found for {maxprod}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user