In an interview I was given this questions:
Write a function to print first n prime numbers
The function looks like this:
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?