Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one.
For example, the sequence for n=5 is as follows: 5 → 16 → 8 → 4 → 2 → 1
Your task is to simulate the execution of the algorithm for a given value of n.
The only input line contains an integer n.
Print a line that contains all values of n during the algorithm.
Input:
5
Output:
5 16 8 4 2 1
Look at what happens to the number in each step:
You don't need to store all the numbers. Just process them one by one and print as you go.
Keep repeating the process until the number becomes 1. The sequence always terminates at 1.
For n = 5:
This problem asks us to implement the Collatz conjecture sequence, also known as the 3n+1 problem.
The algorithm is straightforward:
#include<bits/stdc++.h>
using namespace std;
#define INF 2147483647
#define INFL 9223372036854775807
#define pii pair<int,int>
#define F first
#define S second
#define mp make_pair
#define pb push_back
#define ll long long
#define ull unsigned long long
#define M 1000000007
#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL); cout.tie(NULL);
#define take(x) scanf("%d",&x)
#define DE(x) printf("\ndebug %d\n",x);
#define vout(x) for(int i=0;i<x.size();i++) cout<<x[i]<<" ";
#define pie acos(-1)
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main(){
int t = 1;
//cin>>t;
while(t--){
ll n;
cin>>n;
while(n>1){
printf("%lld ",n);
if( n%2 == 0 ) n/=2;
else n = n*3+1;
}
cout<<1;
}
}