Two lap of PAT & Otsu grade -B1001

1001 killed attractiveness of the (3n + 1) guess (15 points)

Kharazi (Callatz) guess:

For any positive integer  n, if it is even, then it halved; if it is odd, then the  . 3 n- + . 1 cut by half. This has been repeatedly cut, finally got to get a step in  the n- = 1.

Given either a positive integer of not more than 1,000  n, simply count the number, how many steps (cut a few) need to get  the n- = 1?

Input formats:

Each test comprises a test input, i.e., it gives a positive integer  value of n.

Output formats:

Outputted from the  calculation of the required number of steps to n 1.

Sample input:

3
 

Sample output:

5
/*这个题目很简单,实质上就是对输入整数N进行判断,若N为偶数则N/=2,若N为奇数,则N=(3*N+1)/2,循环调用这一算法步骤,直至N=1为止,输出计数变量的值。*/
 1 #include <stdio.h>
 2 
 3 int main(void)
 4 {
 5     int n,x;
 6     int cnt=0;
 7 //    int *p = n;
 8     scanf("%d",&n);
 9     while ( n!=1 ) {
10         if ( n%2 == 0 ) {
11             n = n/2;
12             cnt++;
13         } else {
14             n = (n*3+1)/2;
15             cnt++;
16         }
17     }
18     printf("%d\n",cnt);
19     return 0;
20 }

 

 

Guess you like

Origin www.cnblogs.com/hdu-linux-Soc-AI-IC/p/12559087.html