当前位置:网站首页>PAT乙级 1001 害死人不偿命的(3n+1)猜想
PAT乙级 1001 害死人不偿命的(3n+1)猜想
2022-08-01 04:38:00 【早睡身体好hh】
题目链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805325918486528
题目描述
卡拉兹(Callatz)猜想:
对任何一个正整数 n n n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把 ( 3 n + 1 ) (3n+1) (3n+1) 砍掉一半。这样一直反复砍下去,最后一定在某一步得到 n = 1 n=1 n=1。卡拉兹在 1950 1950 1950 年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,一心只证 ( 3 n + 1 ) (3n+1) (3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……
我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过 1000 1000 1000 的正整数 n n n,简单地数一下,需要多少步(砍几下)才能得到 n = 1 n=1 n=1 ?
输入格式
每个测试输入包含 1 1 1 个测试用例,即给出正整数 n n n 的值。
输出格式
输出从 n n n 计算到 1 1 1 需要的步数。
输入样例
3
输出样例
5
题目解析
思路
本题属于简单模拟题。
根据题意,在 while
循环中分别对奇数和偶数进行不同的操作,同时记录循环的次数。while
循环退出时,输出循环次数即可。
位运算
位运算的好处是速度极快,其运行效率比除法、取余高很多。
判断 n n n 是奇数:n % 2 == 1
或 n & 1 == 1
判断 n n n 是偶数:n % 2 == 0
或 n & 1 == 0
n n n 乘以 2 2 2 :n = n * 2
或 n = n << 1
n n n 除以 2 2 2 :n = n / 2
或 n = n >> 1
C/C++代码
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int cnt = 0;
while (n != 1)
{
if (n & 1) n = (3 * n + 1) >> 1;
else n = n >> 1;
cnt++;
}
cout << cnt << endl;
return 0;
}
边栏推荐
- /etc/fstab
- In the shake database, I want to synchronize the data of the source db0 to the destination db5, how to set the parameters?
- 7 行代码搞崩溃 B 站,原因令人唏嘘!
- mysql中解决存储过程表名通过变量传递的方法
- typescript25 - type assertion
- Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
- 最新 955 不加班的公司名单
- Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
- UE4 制作遇到的问题
- Unity's primary method for implementing PlanarReflection under the BuildIn rendering pipeline
猜你喜欢
Flutter "Hello world" program code
Difference Between Compiled and Interpreted Languages
智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
Passive anti-islanding-UVP/OVP and UFP/OFP passive anti-islanding model simulation based on simulink
博客系统(完整版)
Excel做题记录——整数规划优化模型
The maximum quantity leetcode6133. Grouping (medium)
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
Mysql基础篇(Mysql数据类型)
随机推荐
李迟2022年7月工作生活总结
Message queue design based on mysql
API Design Notes: The pimpl trick
Software Testing Weekly (Issue 82): In fact, all those who are entangled in making choices already have the answer in their hearts, and consultation is just to get the choice that they prefer.
typescript27 - what about enumeration types
The 16th day of the special assault version of the sword offer
typescript28 - value of enumeration type and data enumeration
Optional parameters typescript19 - object
基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置
2. # code comments
typescript23-元组
A way to deal with infinite debugger
leetcode:126. Word Solitaire II
风险策略调优中重要的三步分析法
Logitech Mouse Experience Record
25. 这三道常见的面试题,你有被问过吗?
lambda
软件测试周刊(第82期):其实所有纠结做选择的人心里早就有了答案,咨询只是想得到内心所倾向的选择。
深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!
How to write a high-quality digital good article recommendation