它是Eratosthenes筛网的有效代码吗?

时间:2018-07-17 15:32:08

标签: c++ algorithm primes sieve-of-eratosthenes

我最近学习了Eratosthenes的Sieve来查找素数。知道方法后,我为此编写了代码。
对于Eratosthenes筛网来说,它将是有效的C ++代码吗?

#include <iostream>
using namespace std;

int main()
{
int n;
cin>>n;
bool array[n];

for(int i=2;i<=n;i++)
{
    array[i]=true;
}

   for(int i=2;i<=n/2;i++)
   {
      for(int j=i+1;j<=n;j++)
      {
         if(array[j]==true)
         {
            if(j%i==0)
            array[j]=false;
         }
      }
   }

  for(int k=2;k<=n;k++)
  {
    if(array[k]==true)
    cout<<k<<" ";
  }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

不。这不是Eratosthenes的筛子。 Eratosthenes筛子中没有分隔(j % i == 0