Last active
July 19, 2021 08:25
-
-
Save betaprojects/d8efef3afbd0ee1d94df8cbcf2d23442 to your computer and use it in GitHub Desktop.
Project Euler & HackerRank problem 14 solution: Longest Collatz sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
c = [1] | |
def collatz(_): | |
cx = [0, 1] + [0]*5000000 | |
def d(n): | |
if n>5000000: return d((3*n + 1)//2 if n&1 else n//2) + 1 | |
if not cx[n]: cx[n] = d((3*n + 1)//2 if n&1 else n//2) + 1 | |
return cx[n] | |
m = 0 | |
for n in range(2, 5000001): | |
q = d(n) | |
if q>=m: c.append(n); m = q | |
return c[::-1] | |
c = collatz(0) | |
for _ in range(int(input())): | |
i = int(input()) | |
print (min(c, key=lambda x:x>i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment