当前位置:网站首页>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;
}
边栏推荐
- August 22 Promotion Ambassador Extra Reward Rules
- typescript22-接口继承
- typescript24 - type inference
- Input input box cursor automatically jumps to the last bug after the previous input
- 智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
- The kernel's handling of the device tree
- leetcode:126. Word Solitaire II
- Flutter "Hello world" program code
- Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)
- Passive anti-islanding-UVP/OVP and UFP/OFP passive anti-islanding model simulation based on simulink
猜你喜欢

Passive anti-islanding-UVP/OVP and UFP/OFP passive anti-islanding model simulation based on simulink

The method of solving stored procedure table name passing through variable in mysql

怀念故乡的月亮

typescript19-对象可选参数

数组问题之《两数之和》以及《三数之和 》

This article takes you to understand the past and present of Mimir, Grafana's latest open source project

C# | 使用Json序列化对象时忽略只读的属性

罗技鼠标体验记录

Hackers can how bad to what degree?

Logitech Mouse Experience Record
随机推荐
Valentine's Day Romantic 3D Photo Wall [with source code]
请问shake数据库中想把源的db0的数据同步到目的db5,参数怎么设置呢?
Make your Lottie support word wrapping in text fields
API Design Notes: The pimpl trick
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
typescript20-接口
The kernel's handling of the device tree
typescript26-字面量类型
Unity's primary method for implementing PlanarReflection under the BuildIn rendering pipeline
RSA主要攻击方法
风险策略调优中重要的三步分析法
【愚公系列】2022年07月 Go教学课程 024-函数
mysql中解决存储过程表名通过变量传递的方法
2. # code comments
MySQL4
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
Invalid classes inferred from unique values of `y`. Expected: [0 1 2], got [1 2 3]
高数 | 【重积分】线面积分880例题
解决ffmpeg使用screen-capture-recorder录屏,有屏幕缩放的情况下录不全的问题
认真对待每一个时刻