Algorithm 为什么我自己的Eratosthenes算法实现会陷入无限循环?

Algorithm 为什么我自己的Eratosthenes算法实现会陷入无限循环?,algorithm,loops,sieve-of-eratosthenes,sieve,Algorithm,Loops,Sieve Of Eratosthenes,Sieve,我正在实现Sieve的算法来寻找n以下的素数。我无法找出它为什么会进入无限循环 这里我给出了代码片段。请帮忙 for(int j=2;j<=Math.sqrt(n);j++){ if(a[j]==true){ int x=0; for(int p=(j*j+x*j); p<=n;x++){ a[p]=true; } } } for(int j=2;j您的内部循环正在检查p但从未更改它您的内部循环正在检查p但从未更改它一些优

我正在实现Sieve的算法来寻找n以下的素数。我无法找出它为什么会进入无限循环

这里我给出了代码片段。请帮忙

for(int j=2;j<=Math.sqrt(n);j++){
  if(a[j]==true){
     int x=0;
     for(int p=(j*j+x*j); p<=n;x++){
        a[p]=true;
     }
  }
}   

for(int j=2;j您的内部循环正在检查p但从未更改它

您的内部循环正在检查p但从未更改它

一些优化建议:

// When j is 2, the bitwise (2 & 1) will be 0, so the cycle increments by 1
// When j is odd (from 3 and above), the cycle goes in steps of 2 
// (thus exploring only odd numbers)
// As a result, this cycle is twice as faster than the one progressing
// in increments of 1 
// See here --------------------V
for(int j=2;j<=Math.sqrt(n);j+=(j & 1 ? 2 : 1)) {
  if(a[j]==true){
     // int x=0; // what for?
     // a sum is cheaper than a multiplication
     // Here --V and here --V
     for(int p=j*j; p<=n;p+=j){
        a[p]=true;
     }
  }
}   
//当j为2时,按位(2&1)将为0,因此循环增量为1
//当j为奇数时(从3到更高),循环按步骤2进行
//(因此只探究奇数)
//因此,这一周期的速度是进展周期的两倍
//以1为增量
//看这里------------------V

对于(int j=2;j一些优化建议:

// When j is 2, the bitwise (2 & 1) will be 0, so the cycle increments by 1
// When j is odd (from 3 and above), the cycle goes in steps of 2 
// (thus exploring only odd numbers)
// As a result, this cycle is twice as faster than the one progressing
// in increments of 1 
// See here --------------------V
for(int j=2;j<=Math.sqrt(n);j+=(j & 1 ? 2 : 1)) {
  if(a[j]==true){
     // int x=0; // what for?
     // a sum is cheaper than a multiplication
     // Here --V and here --V
     for(int p=j*j; p<=n;p+=j){
        a[p]=true;
     }
  }
}   
//当j为2时,按位(2&1)将为0,因此循环增量为1
//当j为奇数时(从3到更高),循环按步骤2进行
//(因此只探究奇数)
//因此,这一周期的速度是进展周期的两倍
//以1为增量
//看这里------------------V

对于(int j=2;j)当您更正它时,请记住加法比乘法便宜,并将内循环写成
for(int p=j*j;pAlso,筛子不应该取第一个未标记为复合的数字并将其所有倍数标记为复合的吗?@biziclop“筛子不应该取第一个未标记为复合的数字吗?”你认为这不会发生在哪里?(第一个非复合的
p
实际上是
j*j
-任何低于
j
的值都会被标记为复合的值)我今天早上很笨,但从定义上看,不是任何
j>1
的复合值:您可能想将标题更新为“Eratosthenes筛”,以便更多的人了解这个问题的含义。此算法不是“筛算法”。当您更正它时,请记住加法比乘法便宜,并将内循环写成
(int p=j*j;pAlso,筛子不应该取第一个未标记为复合的数字,并将其所有倍数标记为复合的吗?@biziclop“筛子不应该取第一个未标记为复合的数字”你认为这不会发生在哪里?(第一个非复合的
p
实际上是
j*j
-如果
j
的值较低,那么任何低于该值的值都会被标记为复合的值)今天早上我很笨,但根据定义,对于任何
j>1
?)你可能想将你的标题更新为“Eratosthenes的筛选”所以越来越多的人意识到这个问题是关于什么的。这个算法不是“筛子算法”。