Advertisement
makispaiktis

Longest Collatz Sequence

Jul 21st, 2020 (edited)
1,742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. def countCollageTerms(n):
  2.     # Counter = 1, because we also count the first number "n" in the chain
  3.     counter = 1
  4.     while n != 1:
  5.         if n % 2 == 0:
  6.             n /= 2
  7.             counter += 1
  8.         else:
  9.             n = 3 * n + 1
  10.             counter += 1
  11.     return counter
  12.  
  13. # MAIN FUNCTION
  14. from timeit import default_timer as timer
  15.  
  16. LIMIT = 10**3
  17. collatz = 0
  18. maxSequenceChain = 0
  19. start = timer()
  20. for n in range(LIMIT):
  21.     value = countCollageTerms(n)
  22.     if value > maxSequenceChain:
  23.         collatz = n
  24.         maxSequenceChain = value
  25.  
  26. end = timer()
  27. print()
  28. print("********  EXECUTION TIME UNTIL " + str(LIMIT) + " = " + str(1000*(end-start)) + "ms  ********")
  29. print("From 1 to " + str(LIMIT) + " the number with the longest Collatz sequence is: " + str(collatz) + ". It contains " + str(maxSequenceChain) + " numbers.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement