Last active
January 2, 2016 19:29
-
-
Save cast42/8350149 to your computer and use it in GitHub Desktop.
Check that Euler's polynomial generates primes for the values 0 to 40.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def isPrime(n): | |
"""Returns True if n is prime http://stackoverflow.com/a/1801446/2987382""" | |
if n == 2 or n==3: return True | |
if n < 2 or n % 2 == 0: return False | |
if n % 3 == 0: return False | |
i = 5 | |
w = 2 | |
while i * i <= n: | |
if n % i == 0: | |
return False | |
i += w | |
w = 6 - w | |
return True | |
# Generate primes using Euler's polynomial x**2+x+41 | |
# Optimized to avoid multiplications | |
primes = [] | |
px = 41 # px contains the value of p(x) = x^2+x+41 | |
x = 0 | |
while isPrime(px): | |
primes.append(px) | |
px += 2*x+2 | |
x += 1 | |
print len(primes), " primes generated by Eulers polynomial x**2+x+41" | |
print primes | |
# Output from 'python euler.py': | |
# | |
# 40 primes generated by Eulers polynomial x**2+x+41 | |
# [41, 43, 47, 53, 61, 71, 83, 97, 113, 131, 151, 173, 197, 223, 251, 281, | |
# 313, 347, 383, 421, 461, 503, 547, 593, 641, 691, 743, 797, 853, 911, 971, | |
# 1033, 1097, 1163, 1231, 1301, 1373, 1447, 1523, 1601] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment