gpt4 book ai didi

c++ - 由于大整数 C++,简单的素数查找器卡住

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:54:14 25 4
gpt4 key购买 nike

几天前,我开始学习 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;
}

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

最佳答案

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

关于c++ - 由于大整数 C++,简单的素数查找器卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22602448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com