Collatz sequence in Python

PythonServer Side ProgrammingProgramming

Suppose we have a positve integer n, we have to find the length of its Collatz sequence. As we know Collatz sequence is generated sequentially where n = n/2 when n is even otherwise n = 3n + 1. And this sequence ends when n = 1.

So, if the input is like n = 13, then the output will be 10 as [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] these is the sequence.

To solve this, we will follow these steps −

  • if num is same as 0, then
    • return 0
  • length := 1
  • while num is not same as 1, do
    • num :=(num / 2) when num mod 2 is 0 otherwise (3 * num + 1)
    • length := length + 1
  • return length

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, num):
      if num == 0:
         return 0
      length = 1
      while num != 1:
         num = (num / 2) if num % 2 == 0 else (3 * num + 1)
         length += 1
      return length
ob = Solution()
print(ob.solve(13))

Input

13

Output

10
raja
Published on 22-Sep-2020 10:59:47
Advertisements