Euler Solution 27

From ProgSoc Wiki

Jump to: navigation, search

Considering quadratics of the form:

   n² + an + b, where |a| < 1000 and |b| < 1000

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.

Solutions to Problem 27

Python by Althalus

Runtime: 30 seconds

import time, math
start_time = time.time()

def isPrime(num):
        for i in range(2,int(math.sqrt(abs(num)))+1):
                if abs(num)%i == 0:
                        return False
        return True

def eval_quad(n,a,b):
        return (n**2+n*a+b)

#a,b = 0,0
most_consecutive = 0
most_a,most_b = 0,0
consecutive = 1

#Brute force time!
#Both a&b positive.
for a in range(1,1001):
        for b in range(1,1001):
                consecutive = 0
                while isPrime(eval_quad(consecutive,a,b)):
                        consecutive +=1
                if consecutive > most_consecutive:
                        most_consecutive,most_a,most_b = consecutive,a,b
#a is negative.
for a in range(1,1001):
        for b in range(1,1001):
                consecutive = 0
                while isPrime(eval_quad(consecutive,-a,b)):
                        consecutive +=1
                if consecutive > most_consecutive:
                        most_consecutive,most_a,most_b = consecutive,-a,b
                        
#SPOILER: Commented out all the loops to start with, and just added loops in til I found the anwer.
#Never ran the following loops, the answer's higher up.
#b is negative
for a in range(1,1001):
        for b in range(1,1001):
                consecutive = 0
                while isPrime(eval_quad(consecutive,a,-b)):
                        consecutive +=1
                if consecutive > most_consecutive:
                        most_consecutive,most_a,most_b = consecutive,a,-b
                         
#Both negive...
for a in range(1,1001):
        for b in range(1,1001):
                consecutive = 0
                while isPrime(eval_quad(consecutive,-a,-b)):
                        consecutive +=1
                if consecutive > most_consecutive:
                        most_consecutive,most_a,most_b = consecutive,-a,-b
                        


print(most_a*most_b)
run_time = time.time() - start_time
print (run_time)
Personal tools