Weird Algorithm - Cses

Weird Algorithm - Cses

Problem Statement:

Consider an algorithm that takes as input a positive integer. If it is even, the algorithm divides it by two, and if it is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this until it is one.

For example, the sequence for n=3 is as follows:


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


Let's see how we can solve this problem, All we have to do is just simulate as it is given in the problem statement i.e just do as given in the problem statement

print the element n

  1. If n is even, then divide it by 2.

  2. If n is odd, then multiply it by 3 and add 1

using namespace std;

int main(){

     int n;
     cin >> n;

     while(n != 1){
          cout << n << " ";
          if(n % 2 == 0){
                n /= 2;
               n = n *3 + 1;
     cout << n << " "; 

In this fashion, we can finally print the number n at the end.