博客
关于我
PAT(Basic Level)1001 (3n+1)猜想
阅读量:558 次
发布时间:2019-03-09

本文共 809 字,大约阅读时间需要 2 分钟。

1001 宝藏大问题(3n+1)猜想(15 分)

卡拉兹(Callatz)猜想:对于任何一个正整数 n,如果它是偶数,那么将它除以2;如果它是奇数,那么将 (3n + 1) 除以2。通过不断重复这个过程,最后肯定会在某一步得到 n=1。

对于给定的任一不超过 1000 的正整数 n,您需要计算从 n 计算到 1 所需的步骤(即砍多少下)

我们的任务是编写一个程序,接受输入 n 的值,计算并输出所需步骤的数量。下面是解决方案的简要说明:

### 方法思路我们可以通过模拟过程来解决这个问题。具体步骤如下:1. 初始化步骤计数器到 0。2. 检查当前数是奇数还是偶数: - 如果是偶数,将其除以 2。 - 如果是奇数,将其转换为 (3n + 1) 并除以 2。3. 每次操作后递增步骤计数器。4. 当结果等于 1 时停止,返回步骤计数器的值。

解决代码

#include 
using namespace std;int getNum() { int a = 0; cin >> a; return a;}int count(int a) { int i = 0; while (a != 1) { if (a % 2) { a = (3 * a + 1) / 2; } else { a = a / 2; } i++; } return i;}int main() { int a, i; a = getNum(); i = count(a); cout << i << endl;}

### 结果示例输入:7输出:11

通过上述方法,我们可以轻松计算出从任意正整数 n 到 1 所需的步骤数。这种方法简单直观,能够快速解决问题。

转载地址:http://slvpz.baihongyu.com/

你可能感兴趣的文章
python | feature_engine,一个实用的 Python 库!
查看>>
python | filelock,一个超酷的 Python 库!
查看>>
python | fire,一个强大的 Python 库!
查看>>
python | flanker,一个神奇的 Python 库!
查看>>
python | flower,一个强大的 Python 库!
查看>>
python | funcy,一个超强的 提供函数式编程工具 Python 库!
查看>>
python | ggplot,一个超强的 Python 库!
查看>>
python | grab,一个强大的 Python 库!
查看>>
python | gunicorn,一个非常实用的 Python 库!
查看>>
python | h5py,一个无敌的关于 HDF5 的 Python 库!
查看>>
python | huey,一个非常厉害的 任务调度 Python 库!
查看>>
python | hypothesis,一个有趣的 Python 库!
查看>>
python | Indico,一个超酷的 Python 库!
查看>>
python | isort,一个有趣的 自动整理导入语句 的Python 库!
查看>>
python | jinja,一个超酷的 Python 库!
查看>>
python | joblib,一个强大的 Python 库!
查看>>
python调用git bash_Python学习第70课-用Git Bash在命令行打开sublime
查看>>
python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
查看>>
python课程的中期报告范文_课题研究中期总结报告范文
查看>>
python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
查看>>