-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCircular primes.py
83 lines (56 loc) · 1.78 KB
/
Circular 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from math import sqrt
from functools import reduce
from time import time
'''
Problem 35
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
'''
def isPrime(number):
if not (number > 2 and number % 2 == 0):
for divisor in range(3, int(sqrt(number)) + 1, 2):
if number % divisor == 0:
return False
return True
else:
return False
def listCheck(l):
for number in l:
if not isPrime(number):
return False
return True
def generateCircularPermutations(l):
number = 1
circularPerms = []
circularPerms.append(l)
length = len(l)
l2 = l.copy()
while number < length:
for i in range(0, length - 1):
l2[i], l2[i + 1] = l2[i + 1], l2[i]
circularPerms.append(l2)
number += 1
l2 = l2.copy()
return list(map(lambda per: reduce(lambda x, y: int(x) * 10 + int(y), per), circularPerms))
def filterPrimes():
sieve = {2: False}
sieve.update({i: False for i in range(3, 1000001, 2)})
for k in list(sieve.keys())[1:]:
if not sieve[k]:
for i in range(k**2, 1000001, 2):
if i % k == 0:
sieve[i] = True
return list(filter(lambda x: sieve[x] == False, sieve.keys()))
def main():
start = time()
primes = filterPrimes()
count = 13
for prime in primes[25:]:
rotations = generateCircularPermutations(list(str(prime)))
if listCheck(rotations):
count += 1
print(count)
print(time() - start)
if __name__ == '__main__':
main()