P1001 害死人不偿命的(3n+1)猜想 (Basic Level)

  为了考浙江的研究生,我来被PAT虐一下,PAT这是PAT最简单的等级——乙。好了,话不多说,看题。

  作为入门级别,第一题还是很友好的。题目一遍下来整个代码的就出来了,比水仙花数还简单。说一下思路:

    首先先看看要我们干什么,哦,n经过几次卡拉兹猜想才能到1,n - > 1, 那应该要个循环。

    那什么是卡拉兹猜想,题目里说了,我就不重复了。从卡拉兹猜想很容易就可以知道 是两个选择条件。

  结合上面所有得出就可以快速的写出代码了。

实现

  

 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 }
非递归

  这道题还有递归解法

 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((num * 3 + 1) / 2);
25     }
26     if (!(num % 2))
27     {
28         callatz((num / 2));
29     }
30     return ++count;
31 }
递归实现

前路多艰,诸君共勉。

  

猜你喜欢

转载自www.cnblogs.com/daker-code/p/11615652.html