-
Notifications
You must be signed in to change notification settings - Fork 0
/
primes.py
64 lines (54 loc) · 1.54 KB
/
primes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from math import sqrt
# Utility function for naive method
def is_prime(num):
flag = True
if num > 1:
i = 2
while i * i <= num:
if (num % i) == 0:
flag = False
break
i += 1
else:
return False
return flag
# utility for Segmented Sieve of Eratosthenes
def cal_low_primes(low_primes, end):
temp = [True] * (end + 1)
l = int(sqrt(end))
for i in range(2, l + 1):
if temp[i]:
for j in range(i * i, l + 1, i):
temp[j] = False
for k in range(2, l + 1):
if temp[k]:
low_primes.append(k)
# main driver class
class PrimeCalculator:
@classmethod
def method1(cls, start, end): # Naive method
res = []
for i in range(start, end + 1):
if is_prime(i):
res.append(i)
return res
@classmethod
def method2(cls, start, end): # Segmented Sieve of Eratosthenes
low_primes = []
cal_low_primes(low_primes, end)
primes = [True] * (end - start + 1)
for i in low_primes:
lower = (start // i)
if start <= 1:
start = i + i
elif (start % i) != 0:
lower = (lower * i) + i
else:
lower = lower * i
for j in range(lower, end + 1, i):
primes[j - start] = False
result = []
for k in range(start, end + 1):
if primes[k - start]:
result.append(k)
return result