筛选Eratosthenes C ++代码

时间:2014-05-24 16:12:25

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

我对编程很新,我刚开始使用C ++

我发现了这个问题,其中涉及将所有素数生成到“n”。这是我的代码,我假设“n”为10.我已经尽力了。如果你们能告诉我什么是错的,我真的很感激。

在单独的blockquote中的for循环无限重复,这意味着i的值未被更新。我使用cout语句来打印值,它是0或1.为什么会发生这种情况?逻辑上有错吗?

#include<iostream> 
#include<cstdlib>

using namespace std;

int main()
{
    int NumList[10], flag[10];
    int i,j;


    for(i = 0; i<10; i++) //Generate a list of numbers from 1 to 10
        NumList[i] = i+1;



    for(i = 0; i<10; i++) // Create a flag array, initialized to 1
        flag[i] = 1;

    for(i=1; i<10; i++)
    {
     if(NumList[i]%2==0)  // Mark all even numbers in the list
        flag[i] = 0;      // since they're not prime
    }
    for(i = 2; i<10; i++)        //Start from 3
{
        if(flag[i]==1)      // Check which numbers are left over
    {
        for(j = NumList[i]-1;j<10; ) //Since index = value-1 in this case
        {
            j+= NumList[i];     //Keep incrementing by value and marking in flag[]
            flag[j] = 0;
        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

代码循环无限,因为您已在以下循环中访问了界限

for(j = NumList[i] - 1; j<10; )
{
    j += NumList[i];
    flag[j] = 0;
}

假设当你的外循环中i = 2时Numlist [i]为3,并且你的内循环中j开始为2,则会发生以下情况:

j takes value 2+3, flag[5] is assigned the value 0, current loop ends check 5 < 10
j takes value 5+3, flag[8] is assigned the value 0, current loop ends check 8 < 10
j takes value 8+3, flag[11] is assigned the value 0, current loop ends check 11 < 10

一旦第三个循环结束(已经修改了标志[11]),所有的赌注都将关闭接下来发生的事情。事实上,你可能会破坏你所定义的其他变量,这些变量生活在flag [11]引用的地址上。

至于使这个问题消失,对你当前逻辑的干扰最小(无论它是什么 - 它看起来不正确)你可以增加flags数组的大小。