【问题标题】:simple prime finder freezing due to large integers C++由于大整数 C++,简单的素数查找器冻结
【发布时间】:2014-05-01 09:34:53
【问题描述】:

几天前我开始自己学习 C++。我刚刚编写了一个程序来查找素数,直到用户输入的值,并将这些值写入文件。该程序适用于高达 100,000 - 500,000 的数字。但是,如果我尝试达到 1,000,000,程序就会冻结。这是我的代码:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
long pp, z,counter,lim,indyCounter;
bool isPrime=false;
ofstream myfile;
myfile.open("E:\\Program Files (x86)\\C++ Programs\\PrimeFinder\\Primes.txt");

cout<<"up to what number would you like to calculate primes? ";
cin>>lim;
cout<<endl;
long ps[lim]; //real-time array of primes

pp=3; //prospective prime
ps[0]=2; //initializing prime array with first prime number
counter=1;
indyCounter=1;

for(int y=1; y<=lim;y++)
{
    ps[y]=1;
}

for(int z=0; z<=lim; z++)
{
    for(int x=0;x<counter;x++)
    {
        if(pp%ps[x]!=0)
        {
            isPrime = true;
        }
        if(pp%ps[x]==0 && ps[x]!=1)
        {
            isPrime=false;
            break;
        }
    }
    if(isPrime)
    {
        ps[indyCounter]=pp;
        indyCounter++;
    }
    counter++;
    pp++;
}

for(int y=0; y<=lim-1;y++)
{
    if(ps[y]!=1)
    {
        myfile<<ps[y]<<endl;
    }
}

myfile.close();
return 0;
}

请原谅我的初学者代码,非常感谢所有建议! 谢谢, 史蒂夫

【问题讨论】:

  • 使用指针代替实时数组。因为数组有分配限制,在一定使用后会损坏。
  • @HeenaGoyal:Wat?数组可能不适合堆栈,但这只会中止程序,不会导致静默损坏。

标签: c++ integer primes freeze largenumber


【解决方案1】:

Windows 上的默认堆栈大小仅为 8MB,而 1000000 个 long 的数组需要 8MB,因此您正在溢出堆栈。你需要在堆上分配你的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多