C++ 无法确定代码在打印113383后停止的原因
我正试图编写编程挑战书中的第一个问题。代码计算从a到b生成的数字的数量。C++ 无法确定代码在打印113383后停止的原因,c++,C++,我正试图编写编程挑战书中的第一个问题。代码计算从a到b生成的数字的数量。如果n是偶数,则新的n是n/2,如果n是奇数,则其3*n+1例如,对于22,它将计算数字2211341752261400105168421,因此数字的数量是16。在打印113383后,代码停止,我输入为1000000 #include <iostream> #include <map> #include <vector> using std::cout; using std::cin;
如果n是偶数,则新的n是n/2,如果n是奇数,则其3*n+1
例如,对于22,它将计算数字2211341752261400105168421,因此数字的数量是16。在打印113383后,代码停止,我输入为
1000000
#include <iostream>
#include <map>
#include <vector>
using std::cout;
using std::cin;
using std::string;
using std::endl;
using std::vector;
using std::map;
map<long,long> solution;
long sequences(long n) {
// returns the number of numbers(including 1) `n`produces till it becomes 1
if(n==1)
return 1;
else{
// assuming n>1
if(solution.find(n)!=solution.end())
return solution.find(n)->second;
long size = 0;
while(n!=1){
if(n%2==0){
n = n/2;
if(solution.find(n)!=solution.end())
return solution.find(n)->second + size;
}
else{
n = 3*n+1;
}
size++;
}
return size+1;
}
}
long sequences(long a,long b){
// returns the maximum numbers produced by numbers from a to b inclusive
long result,max = -1;
if(a<b){
for(long i=a;i<=b;i=i+1){
if(solution.find(i) == solution.end()){
cout<< i << endl;
result = sequences(i);
solution.insert(map<long,long>::value_type(i,result));
}
else{
//i present in solution
result = solution.find(i)->second;
}
if(result>max)
max = result;
}
return max;
}
return -1;
}
int main(int argc, char* argv[]) {
long a,b,max;
cin >> a >> b;
// while(cin>>a>>b){
cout<<a<<" "<<b<<" "<<sequences(a,b)<<endl;
/*}*/
return 0;
}
#包括
#包括
#包括
使用std::cout;
使用std::cin;
使用std::string;
使用std::endl;
使用std::vector;
使用std::map;
地图解;
长序列(长n){
//返回'n'生成的数字(包括1)的数目,直到它变为1为止
如果(n==1)
返回1;
否则{
//假设n>1
if(solution.find(n)!=solution.end())
返回解决方案。查找(n)->秒;
长尺寸=0;
而(n!=1){
如果(n%2==0){
n=n/2;
if(solution.find(n)!=solution.end())
返回解决方案。查找(n)->秒+大小;
}
否则{
n=3*n+1;
}
大小++;
}
返回大小+1;
}
}
长序列(长a、长b){
//返回由从a到b(含a)的数字生成的最大数字
长期结果,最大值=-1;
如果(a>>b;
//而(cin>>a>>b){
cout您可能有溢出错误。对于低于113383的所有数字,有符号长足以在不溢出的情况下计算冰雹序列。但是对于113383的起始值,冰雹序列期间达到的最大值是2482111348。这有点太大,无法保存在有符号长中,其最小上限为(2^31)-1.您可能有溢出错误。对于低于113383的所有数字,有符号长足以计算冰雹序列而不溢出。但对于113383的起始值,冰雹序列期间达到的最大值为2482111348。这有点太大,无法用有符号长来保存,其最小上限为(2^31)-1.为什么不在调试器中单步执行代码?对我来说,它打印493。它不正确吗?为什么不在调试器中单步执行代码?对我来说,它打印493。它不正确吗?