Advertisement
makispaiktis

Project Euler 14 - Longest Collatz Sequence

Aug 10th, 2020 (edited)
1,489
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 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**6
  17. collatz = 0
  18. maxSequenceChain = 0
  19. start = timer()
  20. for n in range(1, 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