Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def collatz_conjecture(num: int, steps=0, biggest=1):
- """
- Given integer, return the number of steps Collatz sequence needed to reach 1 and the biggest term on the way.
- #06
- The solution has to be recursive!
- The Collatz conjecture is a conjecture that concerns a sequence that started with any positive integer n.
- If the previous term is even, the next term is previous term / 2.
- If the previous term is odd, the next term is 3 * previous term + 1.
- The conjecture states that no matter what value of n, the sequence will always reach 1.
- collatz_conjecture(12) -> 9, 16 (sequence is [12, 6, 3, 10, 5, 16, 8, 4, 2, 1], steps - 9, biggest term - 16)
- collatz_conjecture(1) -> 0, 1 (sequence is [1], steps - 0, biggest term - 1)
- collatz_conjecture(27) -> 111, 9232
- collatz_conjecture(670617279) -> 949, 966616035460 (close to the border of RecursionError, but should still work)
- collatz_conjecture(0) -> None
- :return (steps, biggest)
- """
- print(num, steps, biggest)
- # biggest = 0
- # steps = 0
- # tup = (biggest, steps)
- if num < 1:
- return None
- if num == 1:
- return steps, biggest
- if num % 2 == 0:
- return collatz_conjecture(num // 2, steps+1, max(biggest, num))
- elif num % 2 != 0:
- return collatz_conjecture(3 * num + 1, steps+1, max(biggest, num))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement