c++ - 素数程序无缘无故停在 20,031 的素数 225,149。没有错误信息

标签 c++

为什么我的寻找素数的程序可以运行,但在第 20,031 个素数即 225,149 处退出?没有错误消息,并且 x-code 声称程序“以退出代码结束”,因为它通常会这样做。

我的问题不是关于程序本身,它似乎在工作(寻找素数),而是我遇到的限制或计算错误导致它退出。

这个循环是有意无限的,但它按预期打印出 225,149,然后停止并退出,没有错误。它只是退出,就好像它到达了循环的结尾。我试过对迭代设置一个限制并将它一点一点地增加到 10,000,0000,000,但奇怪的是它停止了相同的数字,225,149。

是否有超过计算时间限制或其他原因?

输出的最后一位:程序输出从零开始的素数个数,然后是素数。

20027) 225109 20028) 225119 20029) 225133 20030) 225143 20031) 225149 程序以退出代码结束:0

#include <iostream>
#include <cmath>
using namespace std;

//performs modulus and find remainder return remainder r to void primal
double fmodulus (double n, double d)
{
    double r;
    r= fmod(n, d);
    return r;
 }
//finds prime number using modulus double type modulus function fmod()
void primal()
{
    int count=1;
    double n=3.0, d=2.0;
    for (int i= 0; i>=0; ++i)
    {
        double r;
        r= fmodulus(n, d);

        //if n==d then is prime nymber   
        if (n==d)
        {
            cout<<count<<") "<<n<<endl;
            n++;
            d=2.0;
            count++;
        }

        //if remainder == 0 then not prime number    
        else if (r==0)
        {
            n++;
            d=2.0;
        } 

        //not prime so updates d of modulus increment by 1
        else
        {
            d++;
        }
    }
}


int main(int argc, const char * argv[])
{
    cout<<endl;
    primal();
}

最佳答案

有问题的是 i 每次你进行测试时都会递增。在这种情况下,您可以轻松达到 20 亿次测试。当 i 溢出时,它的值变为负值,因此循环结束。

你可以做 3 种不同的事情来解决这个问题:

  • 首先是改变i的类型,使其成为unsigned intunsigned long long。这些类型总是积极的,你的循环将永远不会结束。区别仅在于 unsigned long long 是用 64 位而不是 32 位编写的。

  • 第二种方法是改变循环中的条件;如果你希望它是无限的,你可以简单地使用1。这是一般的真实情况。

  • 最后一种方法是更改​​您的程序,在第一个循环中插入第二个循环,以确保在每次迭代时测试不同的数字。

关于c++ - 素数程序无缘无故停在 20,031 的素数 225,149。没有错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26082201/

相关文章:

c++ - 如何在编译时在初始化列表中包含不同数量的对象?

c++ - 当整数变量用于在 C++ 中声明数组大小时,错误显示为 "Expression must have a const value"

c++ - C++ 中的 auto_ptr 问题

c++ - 如何在 printf 上创建包装器?

c++ - 如何静态检查模板的类型 T 是否为 std::vector<U>,其中 U 为 float、double 或 integral

C++ 将类型参数包转换为索引参数包

c++ - 合并排序处于无限循环中

c++ - 为什么 pA、pB、pC 不相等?

c++ - Qt C++ ffmpeg 找不到库

c++ - 递归程序不适用于大输入