Calculating phi(k) for 1<k<N

前端 未结 9 1868
花落未央
花落未央 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 20:52

    Is this from Project Euler 245? I remember that question, and I have given up on it.

    The fastest way I found for calculating totient was to multiply the prime factors (p-1) together, given that k has no repeated factors (which was never the case if I remember the problem correctly).

    So for calculating factors, it would probably be best to use gmpy.next_prime or pyecm (elliptic curve factorization).

    You could also sieve the prime factors as Jaime suggests. For numbers up to 1012, the maximum prime factor is below 1 million which should be reasonable.

    If you memoize factorizations, it could speed up your phi function even more.

提交回复
热议问题