Back to Solutions

Weird Algorithm

Explanation

Here, we are given a number n and we need to apply the following operations on it:

  • number is odd? : multiply by 3 and add 1
  • number is even? : divide by 2

And we need to apply those until the number n becomes 1.

This can be solved by a simple while loop and implementing the operations.

Code

n = int(input())

while n > 1:
    print(n, end=" ")
    n = (n * 3 + 1) if n % 2 else (n // 2)

print(1)