- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Collatz sequence in Python
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 −
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))
- C++ program to implement Collatz Conjecture
- Connell sequence in Python
- Python Sequence Types
- Longest Consecutive Sequence in Python
- Python Text Sequence Types
- Python Binary Sequence Types
- Find maximum length Snake sequence in Python
- Program to find nth sequence after following the given string sequence rules in Python
- What is a sequence data type in Python?
- How to iterate by sequence index in Python?
- Program to find number of ways we can select sequence from Ajob Sequence in Python
- Second most repeated word in a sequence in Python?
- Find element position in given monotonic sequence in Python
- Find bitonic point in given bitonic sequence in Python
- How to print the Fibonacci Sequence using Python?