Asked By : user6638
Answered By : Ran G.
- reading the input – $n^2$
- For any prime we find (and we have $n$ of those:)
- mark the input tape according to the Sieve of Eratosthenes: we need to go through approximately $O(nlog n)$ numbers due to the density of primes – $O(nlog n)$
- push the index and write the output – $O(log n)$
- counting exactly $p^i$ steps between two indexes we zero – $O(nlog^2n)$
- Multiplying all primes – $O(n^2log^{1+epsilon}n)$
so the naïve solution above takes $O(n^2) + ntimes [ O(nlog n) + O(nlog^2 n)] + O(n^2log^{1+epsilon} n)= O(n^2log^2n)$. In the above I assumed counting takes $O(nlog^2 n)$ since each step we need to subtract 1 from a $log n$-long number, for every step in the sieve (which we bound to length $O(nlog n)$). The time complexity of that algorithms is $O(n^2log^2 n)$. However, things can get better, as there are other ways of sieving. Assuming a multitape TM, the sieve of up to $k$ can be computed using $O(k/loglog k)$ additions (thus, with $O(klog k/loglog k)$ bit-operations) by [1]. By setting $k=O(nlog n)$, we can compute the sieve with $O(nlog n)$ steps. However, computing the multiplication of $n$ numbers (of length $log n$) will take $n times O(MUL_{log n})$ where $MUL_k$ is the time to multiply two numbers of length $k$. According wikipedia, $MUL_k approx O(nlog n )$ [2]. This step alone is $Omega(n^2log n)$ and I don’t see much hope to get complexity of $O(n^2)$. [1]: A. O. L. Atkin and D. J. Bernstein, “Prime sieves using binary quadratic forms” (free-access), Mathematics of Computation 73 (2004), pp. 1023–1030.
[2]: ignoring the practically constant term of $2^{log^* n}$.
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/9330