Skip to main content

Command Palette

Search for a command to run...

Weird Algorithm - Cses

Published
1 min read
Weird Algorithm - Cses
R

A programming enthusiast trying to give share my knowledge with the community :D

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:

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

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

Solution:

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

#include<bits/stdc++.h>
using namespace std;

int main(){

     int n;
     cin >> n;

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

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

More from this blog

U

Untitled Publication

15 posts

I am a computer science enthusiast who loves to shares his knowledge about data structures and algorithms