在c++中搜索数组中的素数

C++ Array in a prime number search

本文关键字:搜索 c++ 数组      更新时间:2023-10-16

所以我试图回答欧拉项目上的一个问题(问题是:找到10,001质数),并遇到了一个问题,我不知道为什么会发生这种情况。当我运行下面的c++代码时,

#include <iostream>
using namespace std;

int main()
{
    int arr[10001]={2}, term=1, i, num=3;
     while(term!=10001)
    {
        for(i=0; i<term; i++)
        {
            if(num%arr[i]==0){
                break;
            }
        }
        if(i==term){
            arr[term]=num;
            cout<< arr[term]<< " is prime"<< endl;
            term++;
        }
        num++;
    }
    cout<< arr[term]<< endl;
}

我总是让cout<< arr[term]<< endl;打印出任何n++;(在本例中是下一个数字,但如果我将其更改为n=856,则它将打印出该数字)。我不明白为什么数组项会改变,因为我认为它只会在arr[term]=num;执行时改变

你的代码有未定义行为,因为你正在访问数组的边界之外。

当循环中断时,term的值为10001,这是数组arr的第10002个元素,而您的数组内存只分配给10001元素。

打印数组的最后一个元素,执行:

cout<< arr[term - 1]<< endl;

在每次迭代中,执行

arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;

所以当while结束时,term是你上次赋值时使用的另一个

您必须输出arr[term-1]而不是arr[term],因为term在对arr[]赋值结束时递增,因此term变量比10001多1。

编辑代码:

#include <iostream>
using namespace std;

int main()
{
    int arr[10002]={2}, term=1, i, num=3;
     while(term!=10001)
    {
        for(i=0; i<term; i++)
        {
            if(num%arr[i]==0){
                break;
            }
        }
        if(i==term){
            arr[term]=num;
            cout<< arr[term]<< " is prime"<< endl;
            term++;
        }
        num++;
    }
    cout<< arr[term-1]<< endl;
  //Your 'term' variable actually is term + 1, hence, you have
  //to print the element at 'term - 1'.
}