Skip to content

Instantly share code, notes, and snippets.

@Isweet
Created November 3, 2014 01:39
Show Gist options
  • Save Isweet/d88c71b6369439d11d33 to your computer and use it in GitHub Desktop.
Save Isweet/d88c71b6369439d11d33 to your computer and use it in GitHub Desktop.
Cleaner Euler Phi Function
import collections
def next_div(n):
for i in xrange(2, n):
if (n % i == 0):
return i
return n
# d | n, d is prime
def elim(n, p):
c = 0
while (n % p == 0):
n /= p
c += 1
return n, c
# n >= 2
def fact(n):
f = collections.Counter()
while (n != 1):
p = next_div(n)
n, f[p] = elim(n, p)
return f
def phi(f):
r = 1
for b, e in f.iteritems():
r *= (b - 1)*b**(e - 1)
return r
def phi_of(n):
return phi(fact(n))
print phi_of(123456)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment