Here’s the algorithm in question, in pseudocode:
list.add(2)
for (i = 3 to n)
isPrime=true
for each (j in list)
if ((i mod j) = 0)
isPrime=false
break
if (isPrime)
list.add(i)
return list
My TA today told me that this algorithm had a complexity of O(n^2), but I am quite sure that is incorrect, especially given that there are approximately n/ln(n) prime numbers up to any n, so the inner loop would not iterate more than n/ln(n) times on its last iteration if n itsself were prime. However I think it’s actually lower than O(n^2/ln(n)) in reality, but I’m not sure how to determine what it actually is. For example, every even number only iterates the second loop twice.
Among
nnumbers you are checking for being prime there are approximatelyn / ln(n)actually prime numbers which demands alli / ln(i)already found prime numbers to be tried as divisors. Therefore, the complexity of your algorithm isW(n^2 / ln(n)^2)(Wis big-omega) andO(n^2 / ln(n).n^2 / ln(n)^2growths faster thenn * sqrt(n).For reaching
O(n * sqrt(n))time complexity you should use the following pseudocode: