当前位置:网站首页>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;
}
边栏推荐
- Logitech Mouse Experience Record
- 让你的 Lottie 支持文字区域内自动换行
- MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
- PMP 项目沟通管理
- The maximum quantity leetcode6133. Grouping (medium)
- typescript23-元组
- API Design Notes: The pimpl trick
- Advice given by experts with four years of development experience in Flutter tutorial
- 出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
- typescript19-对象可选参数
猜你喜欢

Typescript20 - interface

Flink 1.13 (8) CDC

Visual Studio提供的 Command Prompt 到底有啥用

Interview Blitz 69: Is TCP Reliable?Why?

Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink

leetcode:126. Word Solitaire II

typescript21 - Comparison of Interfaces and Type Aliases

Make your Lottie support word wrapping in text fields

【愚公系列】2022年07月 Go教学课程 023-Go容器之列表

UE4 rays flashed from mouse position detection
随机推荐
mysql中解决存储过程表名通过变量传递的方法
typescript20-接口
typescript24-类型推论
2. # code comments
leetcode:126. Word Solitaire II
基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置
PMP 相关方管理必背总结
时时刻刻保持敬畏之心
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
How to promote new products online?
【愚公系列】2022年07月 Go教学课程 024-函数
Immutable
How to write a high-quality digital good article recommendation
UE4 制作遇到的问题
【目标检测】YOLOv7理论简介+实践测试
产品经理访谈 | 第五代验证码的创新与背景
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
typescript27 - what about enumeration types
Typescript20 - interface
Typescript22 - interface inheritance