Skip to content

Commit 139259a

Browse files
committed
Optimize isPrime and the Sieve of Eratosthenes functions
1 parent 0e04a63 commit 139259a

File tree

2 files changed

+20
-34
lines changed

2 files changed

+20
-34
lines changed

primelib/primelib.py

+20-34
Original file line numberDiff line numberDiff line change
@@ -65,31 +65,24 @@ def isPrime(number):
6565
input: positive integer 'number'
6666
returns true if 'number' is prime otherwise false.
6767
"""
68-
import math # for function sqrt
6968

7069
# precondition
7170
assert isinstance(number, int) and (number >= 0), \
7271
"'number' must been an int and positive"
7372

74-
status = True
75-
7673
# 0 and 1 are none primes.
77-
if number <= 1:
78-
return False
79-
80-
# all even numbers except of 2 are no primes.
81-
if number % 2 == 0 and number > 2:
74+
if number <= 3:
75+
return number > 1
76+
elif number % 2 == 0 or number % 3 == 0:
8277
return False
8378

84-
# if 'number' divisible by 'divisor' then sets 'status' to false.
85-
# lazy evaluation breaks the all loop on first false.
86-
status = all(number % divisor for divisor in range(3, int(math.sqrt(number)) + 1, 2))
87-
88-
# precondition
89-
assert isinstance(status, bool), "'status' must been from type bool"
90-
91-
return status
79+
i = 5
80+
while i * i <= number:
81+
if number % i == 0 or number % (i + 2) == 0:
82+
return False
83+
i += 6
9284

85+
return True
9386

9487
# ------------------------------------------
9588

@@ -102,31 +95,24 @@ def sieveEr(N):
10295
sieve of erathostenes.
10396
10497
"""
98+
from math import sqrt
10599

106100
# precondition
107101
assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2"
108102

109-
# beginList: conatins all natural numbers from 2 upt to N
110-
beginList = [x for x in range(2, N + 1)]
111-
112-
ans = [] # this list will be returns.
113-
114-
# actual sieve of erathostenes
115-
for i in range(len(beginList)):
103+
primes = [True for x in xrange(N + 1)]
116104

117-
for j in range(i + 1, len(beginList)):
105+
for p in xrange(2, sqrt(N) + 1):
106+
if (primes[p]):
107+
for i in xrange(p*p, N + 1, p):
108+
primes[i] = False
118109

119-
if (beginList[i] != 0) and \
120-
(beginList[j] % beginList[i] == 0):
121-
beginList[j] = 0
110+
ret = []
111+
for p in xrange(N + 1):
112+
if primes[p]:
113+
ret.append(p)
122114

123-
# filters actual prime numbers.
124-
ans = [x for x in beginList if x != 0]
125-
126-
# precondition
127-
assert isinstance(ans, list), "'ans' must been from type list"
128-
129-
return ans
115+
return ret
130116

131117

132118
# --------------------------------

primelib/primelib.pyc

-11.5 KB
Binary file not shown.

0 commit comments

Comments
 (0)