Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions solutions/python/collatz-conjecture/2/collatz_conjecture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
Collatz Conjecture.

The rules were deceptively simple. Pick any positive integer.

If it's even, divide it by 2.
If it's odd, multiply it by 3 and add 1.
Then, repeat these steps with the result, continuing indefinitely.

Curious, you picked number 12 to test and began the journey:

12 ➜ 6 ➜ 3 ➜ 10 ➜ 5 ➜ 16 ➜ 8 ➜ 4 ➜ 2 ➜ 1
"""


def steps(number: int) -> int:
"""
Return the number of steps it takes to reach 1 according to
the rules of the Collatz Conjecture.

:param number: any positive integer
:type number: int
:return: number of steps it takes to reach 1
:rtype: int
"""
if number < 1:
raise ValueError("Only positive integers are allowed")

n_steps: int = 0
while number > 1:
# If it's even, divide it by 2
if number % 2 == 0:
# Switch to integer division
# keeps everything as int and avoids precision issues
number = number // 2
# If it's odd, multiply it by 3 and add 1
else:
number = (number * 3) + 1
n_steps += 1

return n_steps