Sieve of eratosthenes error

Sieve of eratosthenes error

本文关键字:error eratosthenes of Sieve      更新时间:2023-10-16

我是个新手,正在努力学习C++。我正在阅读编程:使用C++的原理和实践,在第4章中有一个练习,可以制作一个程序,使用Eratosthenes的筛子来寻找素数,但我的程序不起作用,我不知道为什么。

当我试图编译它时,我得到以下警告:

警告C4018:'<':有符号/无符号不匹配

然后当我运行它时,它崩溃并出现以下调试错误:

R6010-abort()已被称为

我看了很长时间的代码,没有找到错误。我是新来的,所以我不知道signedunsigned到底是什么意思,但我尝试过x的各种输入,比如10、100、1000。

调试器显示:

"ConsoleApplication1.exe中0x759B2EEC处未处理的异常:Microsoft C++异常:内存位置0x0031F8C4处的Range_error。">

这是我的代码:

#include "../../std_lib_facilities.h"
int main()
{
//program to find all prime numbers up to number input
vector<int> list(2,0);          //to skip 0 and 1
int x;
cout << "Find all primes up to: ";
cin >> x;
for (int i = 0; i < (x-1); ++i){
list.push_back(1);      //grow the vector and assigns 1
}
for (int i = 0; i < list.size(); ++i){
if (list[i] == 1){      //find the next prime
int c;
c = i;
while (c < list.size()){
c += i;        //then finds all its multiples and,
list[c] = 0;   //assign 0 to show they can't be primes
}
}
}
for (int i = 0; i < list.size(); ++i){  //goes through the vector
if (list[i] == 1)              //write only primes
cout << i << endl;
}
}

错误的原因是什么?

问题可能出现在这里:

for (int i = 0; i < list.size(); ++i){
if (list[i] == 1){
int c;
c = i;
while (c < list.size()){
c += i;        
list[c] = 0;   //problem is here. On the last loops c+=i is too big           
}
}
}

原因是在最外层的for循环中,您最终会得到i == list.size() - 1。现在,如果c > 1,您将得到c + i > list.size(),那么您将尝试访问list[c+i],这是一个大于素数的list大小的索引。这就是为什么当你为1运行它时,它会工作,但对任何其他更大的数字都会失败。

至于编译器警告,那是因为size()返回一个无符号的size_t,而循环变量i是一个有符号的int。当你比较它们时,这就是编译器所抱怨的。将循环更改为:

for (size_t i = 0; i < list.size(); ++i){

编译器的警告就会消失。

相关文章: