1 题目
卡拉兹(Callatz)猜想:
对任何一个正整数 n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把 (3n+1) 砍掉一半。这样一直反复砍下去,最后一定在某一步得到 n=1。卡拉兹在 1950 年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,一心只证 (3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……
我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过 1000 的正整数 n,简单地数一下,需要多少步(砍几下)才能得到 n=1?
输入格式:
每个测试输入包含 1 个测试用例,即给出正整数 n 的值。
输出格式:
输出从 n 计算到 1 需要的步数。
输入样例:
3
输出样例:
5
2 思路
根据题目的意思,我们可以得出步数S与输入n的关系如下:
- n == 1 时:S(1) = 0;
- n > 1 时:
n为偶数: S(n) = S(n/2) + 1;
n为奇数::S(n) = S((3*n+1)/2) + 1;
由于题目对n的取值做了1000的限定,所以我们可以用递归的方式去解决这道题。
3 代码实现
/******************************************************************************
* Copyright 2019 gruminions. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <iostream>
namespace pat {
namespace basic {
namespace level {
class Solution {
public:
static int GetSteps(int n) {
if (n <= 1) {
return 0;
}
if (n % 2 == 0) {
return GetSteps(n / 2) + 1;
} else {
return GetSteps((n * 3 + 1) / 2) + 1;
}
}
};
} // namespace level
} // namespace basic
} // namespace pat
using pat::basic::level::Solution;
int main(void) {
int n = 0;
std::cin >> n;
std::cout << Solution::GetSteps(n) << std::endl;
return 0;
}