角谷猜想_c++

题目描述

所谓角谷猜想,是指对于任意一个正整数,如果是奇数,则乘 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;
}
好了好了,就这样吧

  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值