Problem
A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer:
- If
nis even, the next number in the sequence isn / 2 - If
nis odd, the next number in the sequence is3n + 1It is conjectured that every such sequence eventually reaches the number1. Test this conjecture.
Bonus: What input n <= 1000000 gives the longest sequence?
Examples
Example 1
| |
Example 2
| |
Solution
Method 1 - Run the simulation
The Collatz sequence is generated by the following rules:
- If the number is even, divide it by 2.
- If the number is odd, multiply it by 3 and add 1. The conjecture states that eventually, the sequence will reach 1.
To test this conjecture, we can implement the sequence generation and print the results.
Approach
- Generate the Sequence: Start from the given number and apply the rules iteratively until reaching 1.
- Track the Sequence: Store the sequence in a list and update based on the rules.
- Bonus Task: Iterate through all numbers up to 1,000,000 to find the number that yields the longest sequence.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(N log N)approximately for generating the sequences, whereNis the starting number. - 🧺 Space complexity:
O(N)for the list that stores the sequence.