码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1001. 害死人不偿命的(3n+1)猜想 (15)

时间:2017-06-03 12:48:04      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:names   c++   pre   class   ==   namespace   clu   实现   stream   

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)

标签:names   c++   pre   class   ==   namespace   clu   实现   stream   

原文地址:http://www.cnblogs.com/eyan422/p/6936778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!