-
Notifications
You must be signed in to change notification settings - Fork 0
/
70.py
44 lines (34 loc) · 1012 Bytes
/
70.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
def primes(n):
L = range(n)
for i in range(n):
if L[i] > 1:
for j in range(2 * i, n, i):
L[j] = 0
return [i for i in L if i > 1]
# To speed things up (quite considerably, actually), we use a cache.
# This could be implemented as a memoization decorator. We preload
# the cache with the primes, as that seems to help quite a lot.
P = primes(10000000)
cache = {1: []}
for p in P:
cache[p] = [p]
def prime_factorization(n):
if n in cache:
return cache[n]
for p in P:
if n % p == 0:
factors = [p] + prime_factorization(n / p)
cache[n] = factors
return factors
def totient(n):
numer, denom = n, 1
for p in set(prime_factorization(n)):
numer *= p - 1
denom *= p
return numer / denom
pairs = []
for n in range(2, 10000000):
phi = totient(n)
if tuple(sorted(str(phi))) == tuple(sorted(str(n))):
pairs.append((n * 1.0 / phi, n))
print sorted(pairs)[0][1]