mirror of
https://github.com/correl/euler.git
synced 2024-11-27 19:19:50 +00:00
Optimized prime finding
git-svn-id: file:///srv/svn/euler@30 e5f4c3ec-3c0c-11df-b522-21efaa4426b5
This commit is contained in:
parent
715e24dcf3
commit
9e2d5b6101
1 changed files with 30 additions and 10 deletions
40
007.py
40
007.py
|
@ -1,15 +1,35 @@
|
||||||
def primes(limit):
|
import math
|
||||||
|
|
||||||
|
def is_prime(n):
|
||||||
|
if n == 1:
|
||||||
|
return False
|
||||||
|
if n < 4:
|
||||||
|
return True
|
||||||
|
if n % 2 == 0:
|
||||||
|
return False
|
||||||
|
if n < 9:
|
||||||
|
return True
|
||||||
|
if n % 3 == 0:
|
||||||
|
return False
|
||||||
|
|
||||||
|
r = math.floor(math.sqrt(n))
|
||||||
|
f = 5
|
||||||
|
while f <= r:
|
||||||
|
if (n % f == 0) or (n % (f + 2) == 0):
|
||||||
|
return False
|
||||||
|
f = f + 6
|
||||||
|
return True
|
||||||
|
|
||||||
|
def primes(max_count = 0, max_value = 0):
|
||||||
|
if not max_count and not max_value:
|
||||||
|
raise Exception('There must be a constraint on how many primes to return!')
|
||||||
primes = [2]
|
primes = [2]
|
||||||
i = 3
|
i = 1
|
||||||
while len(primes) < limit:
|
while (not max_count or len(primes) < max_count) \
|
||||||
is_prime = True
|
and (not max_value or i < max_value):
|
||||||
for p in primes:
|
|
||||||
if i % p == 0:
|
|
||||||
is_prime = False
|
|
||||||
break
|
|
||||||
if is_prime:
|
|
||||||
primes.append(i)
|
|
||||||
i = i + 2
|
i = i + 2
|
||||||
|
if is_prime(i):
|
||||||
|
primes.append(i)
|
||||||
return primes
|
return primes
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
Loading…
Reference in a new issue