[PAT] Basic level 1001 害死人不偿命的(3n+1)猜想

1 题目

卡拉兹(Callatz)猜想:

对任何一个正整数 n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把 (3n+1) 砍掉一半。这样一直反复砍下去,最后一定在某一步得到 n=1。卡拉兹在 1950 年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,一心只证 (3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……

我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过 1000 的正整数 n,简单地数一下,需要多少步(砍几下)才能得到 n=1?
输入格式:

每个测试输入包含 1 个测试用例,即给出正整数 n 的值。
输出格式:

输出从 n 计算到 1 需要的步数。
输入样例:

3

输出样例:

5

2 思路

根据题目的意思,我们可以得出步数S与输入n的关系如下:

  1. n == 1 时:S(1) = 0;
  2. 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值