Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. def collatz_conjecture(num: int, steps=0, biggest=1):
  2. """
  3. Given integer, return the number of steps Collatz sequence needed to reach 1 and the biggest term on the way.
  4.  
  5. #06
  6.  
  7. The solution has to be recursive!
  8.  
  9. The Collatz conjecture is a conjecture that concerns a sequence that started with any positive integer n.
  10. If the previous term is even, the next term is previous term / 2.
  11. If the previous term is odd, the next term is 3 * previous term + 1.
  12. The conjecture states that no matter what value of n, the sequence will always reach 1.
  13.  
  14. collatz_conjecture(12) -> 9, 16 (sequence is [12, 6, 3, 10, 5, 16, 8, 4, 2, 1], steps - 9, biggest term - 16)
  15. collatz_conjecture(1) -> 0, 1 (sequence is [1], steps - 0, biggest term - 1)
  16. collatz_conjecture(27) -> 111, 9232
  17. collatz_conjecture(670617279) -> 949, 966616035460 (close to the border of RecursionError, but should still work)
  18. collatz_conjecture(0) -> None
  19.  
  20. :return (steps, biggest)
  21. """
  22. print(num, steps, biggest)
  23. # biggest = 0
  24. # steps = 0
  25. # tup = (biggest, steps)
  26. if num < 1:
  27. return None
  28. if num == 1:
  29. return steps, biggest
  30. if num % 2 == 0:
  31. return collatz_conjecture(num // 2, steps+1, max(biggest, num))
  32. elif num % 2 != 0:
  33. return collatz_conjecture(3 * num + 1, steps+1, max(biggest, num))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement