Calculating phi(k) for 1<k<N

前端 未结 9 1833
花落未央
花落未央 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:06

    For these kind of problems I'm using an iterator that returns for each integer m < N the list of primes < sqrt(N) that divide m. To implement such an iterator I'm using an array A of length R where R > sqrt(N). At each point the array A contains list of primes that divide integers m .. m+R-1. I.e. A[m % R] contains primes dividing m. Each prime p is in exactly one list, i.e. in A[m % R] for the smallest integer in the range m .. m+R-1 that is divisible by p. When generating the next element of the iterator simply the list in A[m % R] is returned. Then the list of primes are removed from A[m % R] and each prime p is appended to A[(m+p) % R].

    With a list of primes < sqrt(N) dividing m it is easy to find the factorization of m, since there is at most one prime larger than sqrt(N).

    This method has complexity O(N log(log(N))) under the assumption that all operations including list operations take O(1). The memory requirement is O(sqrt(N)).

    There is unfortunately, some constant overhead here, hence I was looking for a more elegant way to generate the values phi(n), but so for I've not been successful.

提交回复
热议问题