problem 14 https projecteuler netproblem14 collatz conjecture start with any positive integer n next term obtained from the previous term as follows if the previous term is even the next term is one half the previous term if the previous term is odd the next term is 3 times the previous term plus 1 the conjecture states the sequence will always reach 1 regardless of starting n problem statement the following iterative sequence is defined for the set of positive integers n n2 n is even n 3n 1 n is odd using the rule above and starting with 13 we generate the following sequence 13 40 20 10 5 16 8 4 2 1 it can be seen that this sequence starting at 13 and finishing at 1 contains 10 terms although it has not been proved yet collatz problem it is thought that all starting numbers finish at 1 which starting number under one million produces the longest chain returns the collatz sequence length for n if n in collatzsequencelengths return collatzsequencelengthsn nextn n 2 if n 2 0 else 3 n 1 sequencelength collatzsequencelengthnextn 1 collatzsequencelengthsn sequencelength return sequencelength def solutionn int 1000000 int result maxcollatzsequencelengthi i for i in range1 n return result1 if name main printsolutionintinput strip returns the collatz sequence length for n returns the number under n that generates the longest collatz sequence solution 1000000 837799 solution 200 171 solution 5000 3711 solution 15000 13255
from __future__ import annotations

COLLATZ_SEQUENCE_LENGTHS = {1: 1}


def collatz_sequence_length(n: int) -> int:
    
    if n in COLLATZ_SEQUENCE_LENGTHS:
        return COLLATZ_SEQUENCE_LENGTHS[n]
    next_n = n // 2 if n % 2 == 0 else 3 * n + 1
    sequence_length = collatz_sequence_length(next_n) + 1
    COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length
    return sequence_length


def solution(n: int = 1000000) -> int:
    

    result = max((collatz_sequence_length(i), i) for i in range(1, n))
    return result[1]


if __name__ == "__main__":
    print(solution(int(input().strip())))