【问题标题】:Sieve of eratosthenes error埃拉托色尼筛法错误
【发布时间】:2014-01-15 02:44:10
【问题描述】:

我是新手,我正在努力学习 C++。我正在阅读Programming: Principles and Practice Using 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;
    }
}

错误的原因是什么?

【问题讨论】:

  • 有关有符号/无符号不匹配的警告可能来自您执行 i
  • 你要求它找到最大的质数?
  • 你的调试器说什么?
  • 我将 int 更改为 unsigned int 并且消息消失了,但对于除 1 之外的任何数字,我仍然收到调试错误。

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


【解决方案1】:

问题可能出在这里:

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 &gt; 1 你会得到c + i &gt; list.size() 然后你尝试访问list[c+i] 这是一个大于list 的素数大小的索引。这就是为什么当你运行它为 1 时它可以工作,但对于任何其他更大的数字都会失败。

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

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

您的编译器警告将消失。

【讨论】:

  • 这正是问题所在,我在 list[c]=0 上方放了一个 if (c
  • 太好了,很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多