Calculating phi(k) for 1<k<N

前端 未结 9 1861
花落未央
花落未央 2020-12-04 20:08

Given a large N, I need to iterate through all phi(k) such that 1 < k < N :

  • time-complexity must be O(N logN)
  • memory-complexity mus
9条回答
  •  感情败类
    2020-12-04 21:12

    Here's an efficient python generator. The caveat is that it doesn't yield the results in order. It is based on https://stackoverflow.com/a/10110008/412529 .

    Memory complexity is O(log(N)) as it only has to store a list of prime factors for a single number at a time.

    CPU complexity is just barely superlinear, something like O(N log log N).

    def totientsbelow(N):
        allprimes = primesbelow(N+1)
        def rec(n, partialtot=1, min_p = 0):
            for p in allprimes:
                if p > n:
                    break
                # avoid double solutions such as (6, [2,3]), and (6, [3,2])
                if p < min_p: continue
                yield (p, p-1, [p])
                for t, tot2, r in rec(n//p, partialtot, min_p = p): # uses integer division
                    yield (t*p, tot2 * p if p == r[0] else tot2 * (p-1), [p] + r)
    
        for n, t, factors in rec(N):
            yield (n, t)
    

提交回复
热议问题