1

In an interview I was given this questions:

Write a function to print first n prime numbers

The function looks like this:

Live on ideone

while (true) {
  boolean isPrime = true; 
  for (int divisor = 2; divisor <= (int)(Math.sqrt(number)); divisor++) {
    if (number % divisor == 0) {
      isPrime = false;      
      break;
    }
  }
  number++;
  if(isPrime) {
    System.out.print(number + " ");
    primes++;
  }

  if (primes == n)
      break;
}

A simple complexity analysis could led to O(n√n)
But the interviewer said that the outerloop doesn't go to simply n because for example to find the first 100 prime numbers we need to loop to 541 (that is the 100th prime numbers)

So how do we express the time complexity given this?

giò
  • 3,402
  • 7
  • 27
  • 54
  • 3
    As a side note: I would prefer to see `divison*divisor <= number` as opposed to calling `Math.sqrt()` and type casting. – blazs Apr 07 '16 at 09:51

1 Answers1

5

Answering this takes high math, namely the distribution law of the prime numbers. It tells you (https://en.wikipedia.org/wiki/Prime_number_theorem) that the value of the n-th prime number is about n.log(n).

Then your complexity is O(n√n.log(n)√log(n)).


I may turn out that this bound is pessimistic, because not all iterations run until √n. For instance, even numbers are detected immediately. For a tighter bound, you would need the distribution law of the smallest factor of the integers.

  • 1
    It's a very well-known fact. If you took a cryptography course that covered RSA you would've learned about this. Perhaps you claimed something like that on your CV (e.g. cryptography) and then they decided to test you on that. – blazs Apr 07 '16 at 09:52
  • 2
    I agree. You could have answered "I can't give a precise answer because I don't know the relation between `n` and the `n`-th prime". –  Apr 07 '16 at 09:52
  • @Yves: that's what I said – giò Apr 07 '16 at 09:52
  • @giò: the dot is there to disambiguate, that should be enough. (And you will have no trouble establishing the formula on your own.) –  Apr 07 '16 at 10:03