PAT 1001. 害死人不偿命的(3n+1)猜想 (15)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 1001. 害死人不偿命的(3n+1)猜想 (15)相关的知识,希望对你有一定的参考价值。
C++实现
1 #include <iostream> 2 #include <math.h> 3 using namespace std; 4 5 int StringToInt(string n) 6 { 7 int result = 0; 8 int count = 1; 9 int tmp = 0; 10 11 //cout << "StringToInt" << endl; 12 13 for(char ch : n) 14 { 15 //cout << ch << endl; 16 //cout << (ch-48) << endl; 17 tmp = pow(10,n.length()-count); 18 count++; 19 20 //cout << "tmp: " << tmp; 21 //cout << " " << pow(10,tmp) << endl; 22 result += (ch-48)*tmp; 23 //cout << result << endl; 24 } 25 //cout << result << endl; 26 return result; 27 } 28 29 void Callatz() 30 { 31 int input; 32 string n; 33 int count = 0; 34 35 //cout<< "please enter the value of n: "; 36 cin>>n; 37 //cout<< "n = " << n << endl; 38 39 input = StringToInt(n); 40 //cout<< "input = " << input << endl; 41 42 while( input != 1 ) 43 { 44 if (input % 2 == 0) 45 input = input/2; 46 else 47 input = (3*input+1)/2; 48 count++; 49 } 50 51 cout << count; 52 } 53 54 55 int main() 56 { 57 Callatz(); 58 return 0; 59 }
Python实现
1 #n = int(raw_input()) 2 n=eval(input("please enter the value of n")) 3 #print(n) 4 count = 0 5 while (n != 1): 6 if (n%2 == 0): 7 n = n/2 8 else: 9 n = (3*n+1)/2 10 #print(n) 11 count += 1 12 print(count)
以上是关于PAT 1001. 害死人不偿命的(3n+1)猜想 (15)的主要内容,如果未能解决你的问题,请参考以下文章
PAT算法题C++实现(Basic)1001 害死人不偿命的(3n+1)猜想