题目描述

所谓角谷猜想,是指对于任意一个正整数,如果是奇数,则乘 33 加 11,如果是偶数,则除以 22,得到的结果再按照上述规则重复处理,最终总能够得到 11。如,假定初始整数为 55,计算过程分别为 1616、88、44、22、11。

程序要求输入一个整数,将经过处理得到1的过程输出来。

输入格式

一个正整数 N(N≤2×106N≤2×1000000)

输出格式

从输入整数到 11 的步骤,每一步为一行,每一步中描述计算过程。

最后一行输出"End"。如果输入为 1,直接输出 "End"。

输入数据 1

5

Copy

输入数据 1

5

Copy

输出数据 1

5*3+1=16
16/2=8
8/2=4
4/2=2
2/2=1
End

Copy

题目来源

等级考试,2020 年 12 月,一级,第四题

正文:

这是一种:

#include<iostream>

#include<stdio.h>

using namespace std;

void fun(int a)

{

    if (a == 1) {

        cout << "End";

    }

    else if (a % 2 == 1) {

        int x = a * 3 + 1;

        printf("%d*3+1=%d\n", a, x);

        fun(x);

    }

    else {

        int x = a / 2;

        printf("%d/2=%d\n", a, x);

        fun(x);

    }

}

int main()

{

    int n;

    cin >> n;

    fun(n);

    return 0;

}

还有一种:
#include <iostream>
using namespace std;
int main()
{
    int n;
    cin >> n;
    for (int i;n != 1;i++)
    {
        if (n % 2 == 0)
        {
            cout << n << "/2=" << n/2 << endl;
            n=n/2;
        }
        else
        {
            cout << n << "*3+1=" << n*3+1 << endl;
            n = n*3+1;
        }
    }
    cout << "End";
    return 0;
}
还可以用while:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a;
    cin >> a;
    while (a != 1)
    {
        if (a % 2 == 1)
        {
            cout << a << "*" << 3 << "+" << 1 << "=" << a * 3 + 1 << endl;
            a = a * 3 + 1;
        }
        else
        {
            cout << a << "/" << 2 << "=" << a / 2 << endl;
            a = a / 2;
        }
    }
    cout << "End";
    return 0;
}
好了好了,就这样吧

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐