Link to the problem: Weird Algorithm
Intuition
This problem is a direct implementation of the algorithm described in the problem statement.
Given a number n, we need to apply the following algorithm:
- If
nis even, divide it by 2. - If
nis odd, multiply it by 3 and add 1. - Repeat the process until
nbecomes 1.
Solution
def weird_algorithm(n):
while n != 1:
print(n, end=" ")
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print(n)Geek fact
This is a famous problem in the field math called the Collatz conjecture.
Collatz conjecture is a conjecture in mathematics that states that for any positive integer n, the sequence of numbers generated by the following algorithm will eventually reach 1.
So far, the conjecture has been verified for all positive integers up to 2^68.
Wikipedia link: Collatz conjecture