VOOZH about

URL: https://www.geeksforgeeks.org/dsa/weird-algorithm/

⇱ CSES Solutions - Weird Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Weird Algorithm

Last Updated : 16 Mar, 2024

Consider an algorithm that takes as input a positive integer N. If Nis even, the algorithm divides it by two, and if N isodd, 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:


Output
13 40 20 10 5 16 8 4 2 1

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

Comment
Article Tags:
Article Tags: