알고리즘/CSES
[C++] [CSES] Weird Algorithm (Introductory Problems)
조명인
2023. 2. 9. 10:26
CSES의 첫번째 문제입니다.
1에서 1백만까지의 자연수를 입력으로 받고 1이 될 때까지의 과정을 프린트로 찍는 문제입니다.
홀수일 경우 3배 + 1로 바꾸고 짝수일 경우 2로 나누는 작업을 반복합니다.
Input
The only input line contains an integer n.
Output
Print a line that contains all values of n during the algorithm.
Constraints
- 1≤n≤1000000
Example
Input:
3
Output:
3 10 5 16 8 4 2 1
Code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ll n;
cin >> n;
while (n >= 1){
if (n == 1) {
cout << n;
break;
}
cout << n << " ";
if (n % 2) n = 3 * n + 1;
else n /= 2;
}
}
생각해야 하는 것
- 3배를 하고 1을 더할 경우 int의 범위를 넘어갈 수 있습니다.
- 1을 input으로 받을 경우 1만 출력해야 합니다.