![]() |
VOOZH | about |
Given a positive integer n, the task is to find whether this number reaches 1 after performing the following two operations:-
For example, for n = 12, we get the sequence 12, 6, 3, 10, 5, 16, 8, 4, 2, 1.
Examples:
Input : n = 4
Output : Yes
Input : n = 5
Output : Yes
The idea is to simply follow given rules and recursively call the function with reduced values until it reaches 1. If a value is seen again during recursion, then there is a cycle and we can't reach 1. In this case, we return false.
Yes
The above program is inefficient. The idea is to use Collatz Conjecture. It states that if n is a positive then somehow it will reach 1 after a certain amount of time. So, by using this fact it can be done in O(1) i.e. just check if n is a positive integer or not.
Note that the answer would be false for negative numbers. For negative numbers, the above operations would keep number negative and it would never reach 1.
Yes
Time complexity: O(1)
Auxiliary space: O(1)
We strongly recommend to refer below problem as an exercise:
Maximum Collatz sequence length