[英]Time complexity of generating an array of first n primes?
For a function that takes an integer n
and returns an array of the first n
primes, we have: 对于采用整数n
并返回前n
素数的数组的n
,我们有:
function nPrimes(n) {
let primes = [];
for(let i = 3; primes.length < n - 1; i += 2) {
if (primes.every(prime => i % prime !== 0)) {
primes.push(i);
}
}
primes.unshift(2);
return primes;
}
I'm not sure what the complexity of this algorithm would be. 我不确定该算法的复杂程度。 It seems at least quadratic, because the every
call adds one n
to the runtime complexity where n is the size of the primes array at a given iteration. 这似乎至少是二次的,因为every
调用every
给运行时复杂度增加一个n
,其中n是给定迭代中素数数组的大小。 The unshift
at the end adds an n
but is irrelevant because it will be dwarfed by the leading coefficient. 最后的不unshift
了n
但无关紧要,因为它与前导系数相形见war。
The follow up is, is there a more efficient way of generating such an array? 后续工作是,是否有更有效的方法来生成这样的数组?
This computation is quite arduous. 这种计算是相当艰巨的。
The outer loop is executed n
times and invokes the every
construct for all odd numbers from 3
to the n
th prime. 外循环执行n
次,并调用从3
到第n
个素数的所有奇数的every
构造。
If the every
construct indeed tests all the primes in the list so far, the total workload will be proportional to the sum of k.(P[k+1]-P[k]) = kG[k]
where P[k]
is the k
-th prime and G[k]
the gap until the next prime (when the k
-th prime has been found, the list has k
elements and is tested until the next prime). 如果到目前为止every
构造确实测试了列表中的所有素数,则总工作量将与k.(P[k+1]-P[k]) = kG[k]
的和成正比k.(P[k+1]-P[k]) = kG[k]
其中P[k]
是第k
个素数, G[k]
直到下一个素数为止的间隔(当找到第k
个素数时,列表包含k
元素,并进行测试,直到下一个素数)。
By the prime number theorem, we know that the "average" gap length is on the order of log P[k]
, itself on the order of log(k log k) = log k + log log k
. 通过素数定理,我们知道“平均”间隙长度约为log P[k]
,其本身约为log(k log k) = log k + log log k
。 Then the summation yields O(n.log n)
. 然后求和得出O(n.log n)
。
Now if the every
construct stops as soon as it meets a false condition, its cost is reduced. 现在,如果every
构造一旦满足错误条件便立即停止,则其成本将降低。 In fact, the search will stop at the first prime factor of the tested number, and the total workload will be proportional to the sum of the indexes of the first prime factors of all odd numbers up to P[n] ~ n log n
. 实际上,搜索将在被测数的第一个素数处停止,总工作量将与所有奇数的第一个素数的索引总和成比例,直到P[n] ~ n log n
。
From Web search, it appears that the distribution of the first prime factor of the integers follows a law in 1 / P[k] log P[k]
, for the k
-th prime, ie 1 / k.log k.log(k.log k)
, and we need to sum over all integers m
, using k ~ m / log m
. 从网络搜索看来,整数的第一个素数因子的分布遵循第k
个素数的1 / P[k] log P[k]
1 / k.log k.log(k.log k)
,即1 / k.log k.log(k.log k)
,我们需要使用1 / k.log k.log(k.log k)
k ~ m / log m
对所有整数m
求和。 Neither very rigorous nor easy. 既不严格也不容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.