The 3n + 1 problem UVA - 100
生活随笔
收集整理的這篇文章主要介紹了
The 3n + 1 problem UVA - 100
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
[問題描述]
考慮如下的序列生成算法:從整數 n 開始,如果 n 是偶數,把它除以 2;如果 n 是奇數,把它乘 3 加1。用新得到的值重復上述步驟,直到 n = 1 時停止。例如,n = 22 時該算法生成的序列是:
22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1
人們猜想(沒有得到證明)對于任意整數 n,該算法總能終止于 n = 1。這個猜想對于至少 1 000 000內的整數都是正確的。
對于給定的 n,該序列的元素(包括 1)個數被稱為 n 的循環節長度。在上述例子中,22 的循環節長度為 16。輸入兩個數 i 和 j,你的任務是計算 i 到 j(包含 i 和 j)之間的整數中,循環節長度的最大值。
[輸入]
輸入每行包含兩個整數 i 和 j。所有整數大于 0,小于 1 000 000。
[輸出]
對于每對整數 i 和 j,按原來的順序輸出 i 和 j,然后輸出二者之間的整數中的最大循環節長度。這三個整數應該用單個空格隔開,且在同一行輸出。對于讀入的每一組數據,在輸出中應位于單獨的一行。
[樣例輸入]
1 10
100 200
201 210
900 1000
[樣例輸出]
1 10 20
100 200 125
201 210 89
900 1000 174
代碼
暴力枚舉
#include <iostream> #include <cstring> #include <algorithm> using namespace std; int main() {int i,j,ans[1000];while(cin>>i>>j){memset(ans,0,sizeof(ans));for(int a=i;a<=j;a++){int x=a;while(x!=1){if(x%2==0){x/=2;ans[a]++;}else{x=3*x+1;ans[a]++;}}}int temp=*max_element(ans+i,ans+j);cout<<i<<' '<<j<<' '<<temp+1<<endl;}return 0; }Runtime error
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; int main() {int i,j;while(scanf("%d %d",&i,&j)!=EOF){cout<<i<<' '<<j<<' ';int min,max,ans=0,temp=0;if(i>j){min=j;max=i;}else{min=i;max=j;}for(int a=min;a<=max;a++){int x=a;while(x!=1){if(x%2==0) x/=2;else x=x*3+1;ans++;}ans++;if(a==min)temp=ans;else{if(ans>temp) temp=ans;}ans=0;}cout<<temp<<endl;} }Accepted
總結
以上是生活随笔為你收集整理的The 3n + 1 problem UVA - 100的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信息学奥赛一本通(C++)在线评测系统—
- 下一篇: 历届试题 打印十字图