G - SimpleCollatzSequence

SimpleCollatzSequence

The Simple Collatz Sequence (SCS) starting at an integer n, is defined by the formula:

S(k) = (k/2 if k is even, else (k+1))

The sequence is then n, S(n), S(S(n)), … until the value first reaches 1.
For example, starting at 11, we have:

11 -> 12 -> 6 -> 3 -> 4 -> 2 ->1

The sequence always ends at 1. (Fun Fact: The Hard Collatz Sequence sends odd k to 3*k+1. It is unknown whether that sequence always ends at 1.)
Let A(n) = number of steps in the SCS starting at n. For example, A(11) = 6. Write a program which computes A(n) for a given input n.

Input
Input consists of a single line which contains a positive decimal integer, n, which starts the sequence. n will fit in a 32-bit unsigned integer.

Output
The output consists of a single line that contains the value of A(n), the number of steps in the SCS starting at n.

Sample Input
11

Sample Output
6

Sample Input 2
123456789

Sample Output 2
39

题意:水题,判断当前数字为奇数还是偶数,奇数则n=n+1;偶数则n=n/w;计算该数字最终到达不可分割的最终步数输出即可。
思路:根据题意模拟即可。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
	ll n;
	cin>>n;
	ll cnt=0;
	while(n!=1)
	{
		if(n%2==0)
			n/=2;
		else
			n+=1;
		cnt++;
	}
	cout<<cnt<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值