我正在尝试编写编程挑战书中的第一个问题。该代码计算从a到b生成的数字数。
如果n为偶数,则新n为n / 2,如果n为奇数,则其3 * n + 1。
例如,对于22,它将计算数字22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1等等的数字是16。代码在打印113383后停止,我输入为
1 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;
}
Run Code Online (Sandbox Code Playgroud)
您可能有一个溢出错误。对于113383以下的所有数字,带符号的长度足以计算冰雹序列而不会溢出。但是对于初始值113383,在冰雹序列中达到的最大值为2482111348。这有点太大,无法容纳在有符号长整数中,其最小上限为(2 ^ 31)-1。
| 归档时间: |
|
| 查看次数: |
707 次 |
| 最近记录: |