-
Notifications
You must be signed in to change notification settings - Fork 0
/
Truncatable.py
68 lines (50 loc) · 1.38 KB
/
Truncatable.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
import math
import sys
import Primes
# if 54, return 10. if 234523 return 100000. etc.
def getMagnitude(num):
num = int(num);
return int(math.pow(10, int(math.log10(num))))
def truncLeft(num):
return num%getMagnitude(num)
def truncRight(num):
return int(num/10)
#return True if prime can be truncated to a truncatable
#prime in truncator's direction
def primeTruncatable(num, primesSet, truncator):
num = truncator(num)
while(num != 0):
if(num not in primesSet):
return False
num = truncator(num)
return True
def getTruncPrimes(primes):
primesSet = set(primes);
truncPrimes = [];
#0 is returned when a single-digit prime
#is truncated
primesSet.add(0);
for prime in primes:
if(primeTruncatable(prime, primesSet, truncLeft) and
primeTruncatable(prime, primesSet, truncRight)):
if(getMagnitude(prime) > 1):
truncPrimes.append(prime)
return truncPrimes
def main():
truncPrimes = getTruncPrimes(Primes.getPrimes(1000000));
truncSum = 0;
for p in truncPrimes:
truncSum += p
print truncSum
if __name__ == "__main__":
if(len(sys.argv) > 1 and sys.argv[1] == "test"):
assert getMagnitude(234) == 100
assert getMagnitude(10) == 10
assert getMagnitude(234534) == 100000
assert truncLeft(2345) == 345
assert truncLeft(10) == 0
assert truncLeft(1) == 0
assert truncRight(23453) == 2345
assert truncRight(1) == 0
else:
main()