Open In App

CSES Solutions - Weird Algorithm

Last Updated : 16 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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. Your task is to simulate the execution of the algorithm for a given value of N.

Examples:

Input: N = 13
Output: 13 40 20 10 5 16 8 4 2 1
Explanation:

  • Initially N = 13 which is odd, so N becomes = 40
  • Now, N = 40, which is even, so N becomes = 20
  • Now, N = 20, which is even, so N becomes = 10
  • Now, N = 10, which is even, so N becomes = 5
  • Now, N = 5, which is odd, so N becomes = 16
  • Now, N = 16, which is even, so N becomes = 8
  • Now, N = 8, which is even, so N becomes = 4
  • Now, N = 4, which is even, so N becomes = 2
  • Now, N = 2, which is even, so N becomes = 1

Input: N = 5
Output: 5 16 8 4 1
Explanation:

  • Initially, N = 5, which is odd, so N becomes = 16
  • Now, N = 16, which is even, so N becomes = 8
  • Now, N = 8, which is even, so N becomes = 4
  • Now, N = 4, which is even, so N becomes = 2
  • Now, N = 2, which is even, so N becomes = 1

Approach: To solve the problem, follow the below idea:

The problem can be solved by running a while loop till N is not equal to 1. Inside the while loop, check if N is odd then multiply it by 3 and add 1 to it otherwise if N is even then divide it by 2.

Step-by-step algorithm:

  • Maintain a while loop till N is not equal to 1.
  • Inside the loop,
    • Print N.
    • If N is odd, N = N * 3 + 1
    • Else if N is even, N = N / 2

Below is the implementation of algorithm:

C++
#include <bits/stdc++.h>
#define ll long long int

using namespace std;
int main()
{
    ll N = 13;
    while (N != 1) {
        cout << N << " ";
        // If N is odd, then multiply it by 3 and add 1
        if (N & 1LL)
            N = N * 3 + 1;
        // If N is even, divide it by 2
        else
            N /= 2;
    }
    cout << 1;
}
Java C# JavaScript Python3

Output
13 40 20 10 5 16 8 4 2 1

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article

Similar Reads

three90RightbarBannerImg