Collatz Sequence - Problem
The Collatz sequence (also known as the 3n+1 problem) is a mathematical sequence defined by the following rules:
Starting with any positive integer n:
- If
nis even, divide it by 2 - If
nis odd, multiply by 3 and add 1 - Repeat until you reach 1
Given a positive integer, generate and return the complete Collatz sequence as an array of integers, including the starting number and ending with 1.
Input & Output
Example 1 — Starting with 13
$
Input:
n = 13
›
Output:
[13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
💡 Note:
13 is odd → 3×13+1=40, 40 is even → 40÷2=20, 20→10→5 (odd)→16→8→4→2→1
Example 2 — Starting with 6
$
Input:
n = 6
›
Output:
[6, 3, 10, 5, 16, 8, 4, 2, 1]
💡 Note:
6→3 (odd)→10→5→16→8→4→2→1, taking 9 steps total
Example 3 — Edge Case with 1
$
Input:
n = 1
›
Output:
[1]
💡 Note:
Starting with 1 immediately satisfies the stopping condition
Constraints
- 1 ≤ n ≤ 106
- The sequence will always eventually reach 1 (Collatz conjecture)
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code