今天给大家讲一道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!