1540 - xxx定律

对于一个数n,如果是偶数,就把n砍掉一半;如果是奇数,把n变成 3*n+ 1后砍掉一半,直到该数变为1为止。

请计算需要经过几步才能将n变到1,具体可见样例。

题目输入

测试包含多个用例,每个用例包含一个整数n,当n为0 时表示输入结束。(1<=n<=10000)

题目输出

对于每组测试用例请输出一个数,表示需要经过的步数,每组输出占一行。

输入/输出样例

题目输入

2
7
0

题目输出

1
11

C语言解答

#include<stdio.h>
#include<string.h>
int main()
{
    int x,s=0;

    while(scanf("%d",&x),x)
    {

        for(s=0;x>1;)
        {
            if(x%2==0)
            {
                x=x/2;
                s++;

            }else
            {
                x=3*x+1;
                x=x/2;
                s++;
            }
        }
        printf("%d\n",s);
    }
}

C++解答

#include <cstdio>

int cal(int x) {
    if (1 == x)
        return 0;
    if (x & 1) x = x * 3 + 1;
    return cal(x / 2) + 1;
}

int main() {
    //freopen("data.in", "r", stdin);
    //freopen("data.out", "w", stdout);
    int n;
    while (EOF != scanf("%d", &n)) {
        if (0 == n)
            break;
        printf("%d\n", cal(n));
    }
    return 0;
}

时间限制 1 秒
内存限制 32 MB
讨论 统计
上一题 下一题