Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Collatz sequence in Python
The Collatz sequence (also known as the 3n+1 problem) is a mathematical sequence where we repeatedly apply rules to a positive integer until it reaches 1. For any positive integer n:
- If n is even: n = n/2
- If n is odd: n = 3n + 1
- Continue until n = 1
For example, if n = 13, the sequence is: [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] with a length of 10.
Algorithm Steps
To find the length of a Collatz sequence ?
- If num is 0, return 0
- Initialize length = 1
- While num is not equal to 1:
- Apply the Collatz rule: num = num/2 if even, else 3*num + 1
- Increment length by 1
- Return the total length
Implementation
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))
10
Step-by-Step Example
Let's trace through the sequence for n = 13 ?
def collatz_sequence(n):
sequence = [n]
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(n)
return sequence
# Generate and display the sequence
result = collatz_sequence(13)
print(f"Sequence: {result}")
print(f"Length: {len(result)}")
Sequence: [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] Length: 10
Alternative Implementation
Here's a more concise function-based approach ?
def collatz_length(n):
if n == 0:
return 0
length = 1
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
length += 1
return length
# Test with different values
test_values = [1, 5, 13, 27]
for val in test_values:
print(f"Collatz length of {val}: {collatz_length(val)}")
Collatz length of 1: 1 Collatz length of 5: 6 Collatz length of 13: 10 Collatz length of 27: 112
Key Points
- Use integer division (//) instead of float division (/) for even numbers
- The sequence always reaches 1 for positive integers (unproven conjecture)
- Length includes the starting number and ending 1
- Time complexity varies greatly depending on the input value
Conclusion
The Collatz sequence is implemented by repeatedly applying the 3n+1 rule until reaching 1. Use integer division for even numbers and count each step to find the sequence length.
Advertisements
