角谷定理。输入一个自然数,若为偶数,则把它除以2,若为奇数,则把它乘以3加1。经过如此有限次运算后,总可以得到自然数值1。求经过多少次可得到自然数1。
如:输入22
输出 22 11 34 17 52 26 13 40 20 10 5 16 8 4 1
STEP=16
<span style="color:#cc33cc">/*
File name:角谷定理.cpp
Author:杨柳
Date:2017/5/22
IDE:DEV-c++
*/
/*f(n){ 1 n=1 i=一步 </span>
f(n/2) n=偶数 i++
f(n*3+1) n=奇数 i++
}
*/
#include<iostream>
using namespace std;
int static n=1;
int step(int num){
if(num==1){
cout<<num;
return n;
}
if(num%2==0){
cout<<num<<" ";
step(num/=2);//为偶数除2
n++;
}
else{
cout<<num<<" ";
step(num=num*3+1);//为奇数乘以3加1
n++;
}
}
int main(){
int number;
cout<<"please input a number:"<<endl;
cin>>number;
step(number);
cout<<endl<<"step="<<n<<endl;
return 0;
}
#include<iostream>
using namespace std;
int static n=1;
int step(int num){
if(num==1){
cout<<num;
return n;
}
if(num%2==0){
cout<<num<<" ";
step(num/=2);//为偶数除2
n++;
}
else{
cout<<num<<" ";
step(num=num*3+1);//为奇数乘以3加1
n++;
}
}
int main(){
int number;
cout<<"please input a number:"<<endl;
cin>>number;
step(number);
cout<<endl<<"step="<<n<<endl;
return 0;
}