How many elements would be contained in the set of reduced proper fractions for d 1,000,000? Solution -------- A numerator/denominator pair that are not relatively prime can be reduced. Thus, we wan't to add up all of the relatively prime numerator/denominator pairs. The number of such numerators for each denominator is the Euler Totient function, which takes as input the prime factors of the denominator. We collect the prime factors, and add up the totients """ from util import totient top = 1000001 #prime factors of numbers fs = [[] for i in range(top)] for i in xrange(2, top): if fs[i]: continue for j in xrange(i, top, i): fs[j].append(i) #totients for each number. Skip 0,1 ts = [totient(i, fs[i]) for i in range(2, top)] #the answer print sum(ts)
import psyco import util primes = util.prime_sieve(1000000) sum = 0 for i in range(2, 1000001): sum += util.totient(i, primes) print sum