Weird Algorithm

今天给大家讲一道cses上的题目,现做现发(今天没有水博客) 

话不多说,上题目!

  • Time limit: 1.00 s
  • Memory limit: 512 MB

Consider an algorithm that takes as input a positive integer nn. If nn is even, the algorithm divides it by two, and if nn is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until nn is one. For example, the sequence for n=3n=3 is as follows:

3→10→5→16→8→4→2→13→10→5→16→8→4→2→1


Your task is to simulate the execution of the algorithm for a given value of nn.

Input

The only input line contains an integer nn.

Output

Print a line that contains all values of nn during the algorithm.

Constraints

  • 1≤n≤1061≤n≤106

Example

Input:
3

Output:
3 10 5 16 8 4 2 1

翻译

时间限制:1.00s

内存限制:512mb
考虑一个算法,它以一个正整数n作为输入。如果n是偶数,算法将它除以2,如果n是奇数,算法将它乘以3并加1。算法重复这个过程,直到n = 1。例如,n=3的序列如下:
3-10-5-16-8-4-2-1

你的任务是模拟给定n值时算法的执行。

输入

唯一的输入行包含一个整数n。

输出

打印一行包含算法期间的所有n值。

数据范围
1≤n≤10^6
例子

样例输入:
3.

样例输出:
3 10 5 16 8 4 2

直接上代码!

#include <bits/stdc++.h>
using namespace std;
 
int main(){
	long long n;
	cin >> n;
	cout << n << " ";
	while(n != 1){
		if(n % 2 == 0){
			n /= 2;
			cout << n << " ";
			
		}else{
			n = n * 3 + 1;
			cout << n << " ";
		}
	} 
	return 0;
}

 感觉写这道题唯一要注意的就是 n要开long long!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bamboo_Day

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值