UVA694 - The Collatz Sequence
# 问题描述
3n+1问题,A序列中,从第一项a开始,如果a为偶数,则下一项为a=a/2,否则a=3*a+1,直到a=1后停止,问在限定范围内该序列有多少个?
# 思路
根据题意模拟,如果超出给定范围或者序列结束,输出结果。题目中存在陷阱,它的数据范围要比int类型大,但是又要求能够被32位机存储,所以使用的数据类型为long或者long long
# 代码
#include <iostream>
using namespace std;
int main()
{
long a,L,c=0,k=0,A;
while(cin>>a>>L)
{
A=a;
c=1;
if(a==-1&&L==-1)
break;
while(a>1)
{
if(a%2==1)
a=a*3+1;
else
a=a/2;
if(a>L)
break;
c++;
}
cout<<"Case "<<++k<<": A = "<<A<<", limit = "
<<L<<", number of terms = "<<c<<endl;
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
编辑 (opens new window)
上次更新: 2022/05/18, 19:03:08