P1001 killed attractiveness of the (3n + 1) guess (Basic Level)

  In order to test students in Zhejiang, I was about abuse PAT, PAT PAT This is the most simple level - B. Well, I did not talk much to say, look at the title.

  As an entry-level, the first question is very friendly. The title again down the entire code came out, even simpler than a few daffodils. Talk about ideas:

    First, take a look at what we want to, oh, n after several Kharazi guess to get to 1, n -> 1, it should be cycles.

    So what is Kharazi guess the title says, I will not repeat. From Kharazi I guess it is easy to know two selection criteria.

  All of the above combined results can quickly write code.

Realization :

  

 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     int num;
 6 
 7     while (~scanf("%d", &num))
 8     {
 9         int count = 0;
10         while (num != 1)
11         {
12             if (num % 2)
13             {
14                 num = (3 * num + 1) / 2;
15             }
16             else
17             {
18                 num /= 2;
19             }
20             count++;
21         }
22         printf("%d\n", count);
23     }
24     return 0;
25 }
Non-recursive

  This question is also recursive solution

 1 #include <stdio.h>
 2 
 3 int callatz(int num);
 4 int count = 0;
 5 int main()
 6 {
 7     int num;
 8 
 9     while (~scanf("%d", &num))
10     {
11         count = 0;
12         printf("%d\n", callatz(num));
13     }
14     return 0;
15 }
 16  int callatz ( int num)
 17  {
 18      if ( 1 == num)
 19      {
 20          return count;
21      }
 22      if (num% 2 )
 23      {
 24          callatz ((Surely * 3 + 1 ) / 2 );
25      }
 26      if (! (Whether% 2 ))
 27      {
 28          callatz ((whether he / 2 ));
29     }
30     return ++count;
31 }
Recursive

Anterior and more difficult, the party of mutual encouragement.

  

Guess you like

Origin www.cnblogs.com/daker-code/p/11615652.html