当前位置:网站首页>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;
}
边栏推荐
- Make your Lottie support word wrapping in text fields
- 阿叶的目标
- 7月编程排行榜来啦!这次有何新变化?
- Introduction to Oracle
- UE4 从鼠标位置射出射线检测
- Unity's primary method for implementing PlanarReflection under the BuildIn rendering pipeline
- A way to deal with infinite debugger
- Interview Blitz 69: Is TCP Reliable?Why?
- Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)
- typescript20-接口
猜你喜欢
随机推荐
项目风险管理必备内容总结
This article takes you to understand the past and present of Mimir, Grafana's latest open source project
UE4 rays flashed from mouse position detection
Excuse me, only primary key columns can be queried using sql in table storage. Does ots sql not support non-primary keys?
动态规划 01背包
6-23漏洞利用-postgresql代码执行利用
25. Have you been asked these three common interview questions?
leetcode:126. Word Solitaire II
Excel做题记录——整数规划优化模型
MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
MySQL3
Flutter Tutorial 01 Configure the environment and run the demo program (tutorial includes source code)
FFmpeg 搭建本地屏幕录制环境
EntityFramework saves to SQLServer decimal precision is lost
Write a method to flatten an array and deduplicate and sort it incrementally
博客系统(完整版)
Difference Between Compiled and Interpreted Languages
typescript26-字面量类型
2. # code comments
Logitech Mouse Experience Record