验证角谷猜想(利用位运算)

题目描述

数论中有许多猜想尚未解决,其中有一个被称为“角谷猜想”的问题,该问题在五、六十年代的美国多个著名高校中曾风行一时,这个问题是这样描述的:任何一个大于一的自然数,如果是奇数,则乘以三再加一;如果是偶数,则除以二;得出的结果继续按照前面的规则进行运算,最后必定得到一。现在请你编写一个程序验证他的正确性。

输入

题目包含多组测试数据,第一行为测试数据组数N,接着是N行的正整数。

输出

输出验证“角谷猜想”过程中的奇数,最后得到的1不用输出;每个测试题输出一行;每行中只有两个输出之间才能有一个空格;如果没有这样的输出,则输出:No number can be output !。

样例输入

4
5
9
16
11

样例输出

5
9 7 11 17 13 5
No number can be output !
11 17 13 5

分析:
本题不难,按照题目的要求编写代码即可,下面给出两种AC代码。第二种利用了位运算的性质:
奇数 & 1 = 1
偶数 & 1 = 0
x = x / 2等价于x /= 2,也等价于x >>= 1

AC代码1

#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    cin >> n;
    
    while (n--)
    {
        int x;
        cin >> x;
        
        int cnt = 0;//奇数计数器
        while (x != 1)
        {
            if (x % 2 == 0)//x是偶数
            {
                x = x / 2; 
            }
            else
            {
                cout << x << " ";
                
                //每输出一个奇数,计数器加1
                cnt++;
                x = x * 3 + 1;
            }
        }
        
        if (cnt == 0) cout << "No number can be output !";//没有输出1以外的奇数
        cout << endl;
    }
    return 0;
}

AC代码2:

#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int n;//多组测试
    cin >> n;
    
    while (n--)
    {
        int x;
        cin >> x;
        
        int cnt = 0;//奇数计数器
        while (x != 1)
        {
            if (x & 1)//x是寄数
            {
                cout << x << " ";
                cnt++;//计数
                x = x * 3 + 1; 
            }
            else x >>= 1;
        }
        
        if (cnt == 0) cout << "No number can be output !";//没有输出1以外的奇数
        cout << endl;
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值