問題重述:
角谷定理。輸入一個自然數,若爲偶數,則把它除以2,若爲奇數,則把它乘以3加1。經過如此有限次運算後,總可以得到自然數值1。求經過多少次可得到自然數1。
如:輸入22,
輸出 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
STEP=16
題目分析:
根據題意有:
xn+1=xn2, xn%2=0xn+1=xn×3+1, xn%2=1
最後Xlast=1
算法構造:
根據上述公式可以看出:
函數出口:Xlast=1
函數體:
xn+1=xn2, xn%2=0xn+1=xn×3+1, xn%2=1
根據當前的數字判斷其奇偶性,若爲偶數,則把它除以2,若爲奇數,則把它乘以3加1,然後再次遞歸判斷,直到最後一次的數字爲1時跳出函數
算法實現:
#include<iostream>
using namespace std;
/*
Author:Qiaoxue Zheng
Date:2018/11/15
Dscribtion:To get the steps according to Kakutani Theory
*/
/*
Function:Kakutani
Parameter:
number:natural number
Return:steps
*/
int Kakutani(int number) {
int count = 0;
cout << number<<" ";//output each number
count++;//count steps
//exit,the last number is 1
if (number == 1) {
return count;
}
//body
else {
if (number % 2 == 0) {//Even numbers
count += Kakutani(number / 2);
return count;
}
else {//Odd number
count += Kakutani(number * 3 + 1);
return count;
}
}
}
//Main function
int main() {
int number = 0;
cout << "please input a int number:";
cin >> number;
cout<<endl<<"總步數:"<<Kakutani(number)<<endl;
system("pause");
return 0;
}
運行結果: