问题
I was asked this question in an interview. I implemented an algorithm using sieve of eratosthenes concept and an array.
Is there a better way to go about this question For those who dont know the sieve , here is the link:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
EDIT: Best in terms of both time and space complexity. I just told them the flaw of SoE is space complexity. So they asked me if I could do something about it . Here is how the interview went about: 1) Implement a algo that prints prime numbers from 1 to n Ans: I implement using SoE 2) Is this the best way to go about it Ans: ???
回答1:
Well, it depends on what you mean by "best." The Sieve of Eratosthenes is very easy to implement, but the Sieve of Atkin will give you significantly better performance.
So, if "best" means easy to implement and understand, Eratosthenes is the way to go. If "best" means want to show off your skills as a mathematician or have a very fast algorithm, Atkin is the way to go.
回答2:
Well , it only depends on the value of N :
The sieve of Eratosthenes ( Simple Sieve ) is one of the most efficient algorithm to find all primes smaller than n when n is smaller than 10 million ( Means 10^7 ) because Simple sieve requires O(n) linear space. And we know that we can make a global array of maximum size 10^7. So , when n is larger than 10^7 , the Simple Sieve faces issue because an array of size more than 10^7 may not fit in memory.
For n>=10^7 , we can use Segmented Sieve of Eratosthenes because in segmented sieve , we can improve memory consumption from linear to O(√n) space.
Note that time complexity of Segmented Sieve is same as Simple Sieve. The only advantage which segmented sieve have : it is perfect for large ‘n’
回答3:
For a programming interview, no :). There's this though http://en.wikipedia.org/wiki/Sieve_of_Atkin and I'm sure there's probably research papers out there that eek out small optimizations.
来源:https://stackoverflow.com/questions/5329126/is-sieve-of-erathosthens-the-best-algorithm-to-generate-prime-numbers-from-1-to