2800 - 万数归一
对于任一大于1的自然数,若为奇,乘3后加1;若为偶,就用2去除;对于得出的结果继续执行前面的运算,最终一定得到1。不管你信不信,编程验证一下吧。
Input
题目包含多组测试数据,第一行为测试数据组数N,接着是N行的正整数。
Output
输出验证过程中的奇数,最后得到的1不用输出;每个测试数输出一行;每行中只有两个输出之间才能有一个空格;如果没有这样的输出,则输出:No odd number
(对输出格式的说明:每行最后一个数字之后无空格。每行末尾有一个换行)
<span style="font-size:12pt;font-family:';"><br />
Examples
Input
3 5 9 16
Output
5 9 7 11 17 13 5 No odd number
Hint
题目中强调:每行中只有两个输出之间才能有一个空格;
Solution C
#include<stdio.h> int main() { int a[100],b[100]; int i,x,k,m = 0; scanf("%d",&k); for(x = 0;x<k;x++) scanf("%d",&a[x]); for(x = 0;x<k;x++) { int count = 0; if(x>0) printf("\n"); for(i = 1;;i++) { if(a[x] == 1) { break; } else if(a[x]%2 == 0) a[x] = a[x]/2; else if(a[x]%2 == 1) { b[m] = i; if(b[m]>b[0]) printf(" %d",a[x]); else printf("%d",a[x]); m++; a[x] = a[x]*3+1; count = 1; } } if (count==0) printf("No odd number"); } return 0; }
Solution C++
#include<iostream> using namespace std; int main() { int n,temp,i,b[100][100],k[100],t[100],a[100],j; cin>>n; for(i=0;i<n;i++) cin>>a[i]; for(i=0;i<n;i++) { t[i]=0; k[i]=0; temp=a[i]; while(temp!=1) { if(temp%2==1&&temp!=1) { b[i][t[i]]=temp; t[i]++; temp=temp*3+1; k[i]++; } else temp/=2; } if(a[i]%2==1) k[i]--; } for(i=0;i<n;i++) { if(t[i]==0) cout<<"No odd number"; else { for(j=0;j<t[i];j++) { if(j!=t[i]-1) cout<<b[i][j]<<" "; else cout<<b[i][j]; } } if(i<n-1) cout<<"\n"; } return 0; }
Hint
题目中强调:每行中只有两个输出之间才能有一个空格;