由于大整数C++; 几天前我就自学了C++。我刚刚写了一个程序来查找素数,最多一个用户输入的值,并将这些值写入一个文件。该程序可以很好地处理高达100000-500000的数字。但是,如果我试图达到1000000,程序就会冻结。这是我的密码: #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; } #包括 #包括 使用名称空间std; int main() { 长pp、z、计数器、lim、indyCounter; bool isPrime=false; 流文件; myfile.open(“E:\\ProgramFiles(x86)\\C++Programs\\PrimeFinder\\Primes.txt”); 库特林; cout

由于大整数C++; 几天前我就自学了C++。我刚刚写了一个程序来查找素数,最多一个用户输入的值,并将这些值写入一个文件。该程序可以很好地处理高达100000-500000的数字。但是,如果我试图达到1000000,程序就会冻结。这是我的密码: #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; } #包括 #包括 使用名称空间std; int main() { 长pp、z、计数器、lim、indyCounter; bool isPrime=false; 流文件; myfile.open(“E:\\ProgramFiles(x86)\\C++Programs\\PrimeFinder\\Primes.txt”); 库特林; cout,c++,integer,primes,freeze,largenumber,C++,Integer,Primes,Freeze,Largenumber,Windows上的默认堆栈大小只有8MB,1000000个长数组需要8MB,因此堆栈溢出。您需要在堆上分配数组。使用指针而不是实时数组。因为数组有分配限制,在使用某个数组后会损坏。@HeenaGoyal:Wat?该数组可能不会但这只会中止程序,而不会导致静默损坏。

Windows上的默认堆栈大小只有8MB,1000000个长数组需要8MB,因此堆栈溢出。您需要在堆上分配数组。

使用指针而不是实时数组。因为数组有分配限制,在使用某个数组后会损坏。@HeenaGoyal:Wat?该数组可能不会但这只会中止程序,而不会导致静默损坏。