martineau

Collatz sequence in Python

May 11th, 2017
105
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python3
  2. # http://stackoverflow.com/questions/43922426/how-to-write-code-to-find-the-n-th-number-in-the-collatz-sequance
  3.  
  4. # The following is a direct implementation based on what is shown here:
  5. #   https://en.wikipedia.org/wiki/Collatz_conjecture#Statement_of_the_problem
  6.  
  7. def f(a):
  8.     if a % 2 == 0:
  9.         return a//2
  10.     else:
  11.         return 3*a + 1
  12.  
  13. def collatz(a, n):
  14.     for _ in range(n):
  15.         a = f(a)
  16.     return a
  17.  
  18. print(collatz(11, 5))  # -> 13
RAW Paste Data