[英]Complexity of print first n prime number
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)
简单的复杂度分析可能导致
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) 但是面试官说,外循环不会简单地转到
n
因为例如要找到前100个素数,我们需要循环到541(即第100个素数)
So how do we express the time complexity given this? 那么我们如何表达给定的时间复杂度呢?
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)
. 它告诉您( https://en.wikipedia.org/wiki/Prime_number_theorem )第
n
个质数的值约为n.log(n)
。
Then your complexity is O(n√n.log(n)√log(n))
. 那么您的复杂度为
O(n√n.log(n)√log(n))
。
I may turn out that this bound is pessimistic, because not all iterations run until √n. 我可能会发现此界限是悲观的,因为并非所有迭代都运行到√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.
为了获得更紧密的界限,您将需要整数的最小因子的分布定律。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.