B2077 角谷猜想 题解
管理员备注:本题数据已于 2023 年更新,在极限情况下运算过程中可能出现数据溢出 int 的情况,因此请将本题所有题解中的代码运算视作 long long 运算。
#include <bits/stdc++.h>
using namespace std;
long long n;
int main() {
cin >> n;
while (n != 1) {
if (n % 2 != 0) {
cout << n << "*3+1=" << n * 3 + 1 << endl;
n = n * 3 + 1;
} else {
cout << n << "/2=" << n / 2 << endl;
n = n / 2;
}
}
cout << "End" << endl;
return 0;
}
这道题不难,考察的是对循环的运用。这里我们采用 while 循环来做。还要注意一下格式,结尾有 End。
#include<bits/stdc++.h>
using namespace std;
int n;
int main(){
cin>>n;
while(n!=1){//n不为1
if(n%2!=0){//奇数
cout<<n<<"*3+1="<<n*3+1<<endl;
n=n*3+1;
}
else{//偶数
cout<<n<<"/2="<<n/2<<endl;
n=n/2;
}
}
cout<<"End";//结尾输出End
return 0;
}