The Collatz sequence is an intriguing mathematical sequence where a number n
follows a specific set of rules until it eventually reaches 1. In this post, we will create a Python program to generate the Collatz sequence for a given number and count the number of steps required to reach 1.
Problem Description
Given an integer n
, the program should:
- Generate and print the Collatz sequence starting from
n
. - Count and print the number of steps required to reach 1.
Rules for Collatz Sequence
- If
n
is even, divide it by 2:n = n / 2
- If
n
is odd, multiply it by 3 and add 1:n = 3n + 1
This process is repeated until n
becomes 1.
Approach
- Loop Through Sequence: Start with the input number
n
and apply the Collatz rules in a loop untiln
equals 1. - Count Steps: Keep a counter to track the number of steps taken to reach 1.
- Print Each Step: Output each number in the sequence, one per line.
Python Implementation
def collatz_sequence(n):
steps = 0
while n != 1:
print(n)
steps += 1
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print(n) # Print the final 1
print(steps) # Print the number of steps
# Input Handling
n = int(input())
# Generate and print the Collatz sequence
collatz_sequence(n)
Explanation
- While Loop: The loop continues until
n
becomes 1. - Step Counting: A counter
steps
is incremented on each iteration to track the number of steps. - Print Sequence: Each value of
n
is printed before the rule is applied. - Final Outputs: The final 1 and the total number of steps are printed at the end.
Test Cases
Let’s check the function with some test cases:
# Test Case 1
# Input: 5
# Expected Output:
# 5
# 16
# 8
# 4
# 2
# 1
# 5
collatz_sequence(5)
# Test Case 2
# Input: 8
# Expected Output:
# 8
# 4
# 2
# 1
# 3
collatz_sequence(8)
# Test Case 3
# Input: 1
# Expected Output:
# 1
# 0
collatz_sequence(1)
# Test Case 4
# Input: 7
# Expected Output:
# 7
# 22
# 11
# 34
# 17
# 52
# 26
# 13
# 40
# 20
# 10
# 5
# 16
# 8
# 4
# 2
# 1
# 16
collatz_sequence(7)
Conclusion
The Collatz sequence is a fascinating number pattern, and this Python program demonstrates how to generate it and count the steps needed to reach 1. The sequence is easy to compute, and the program handles both small and large input values effectively. Try it out with different starting numbers to see the variety of sequences!