[Solved] Solving Euler #14 with bruteforce in Python [closed]


You could store the intermediate value in a dictionary and do a kind of a dynamic programming.

numbers = {1:0}
max = -1
startMax = -1
for i in range(2, 1000 000):
    n = i
    steps = 0
    while n>=i:
        if n&2 == 0:
            n = n/2
        else:
            n = 3*n + 1
        steps = steps + 1
    # n < i, hence it must already be stored in the dictionary
    steps = steps + numbers[n]
    if steps > max:
        max = steps
        startMax = i
    numbers[i] = steps
    return startMax

Another approach may be to store every number you encounter and always check whether the number you are currently on is in the map. But I guess this may take a bit longer with so many dictionary look-ups:

numbers = {1:0}
max = -1
for i in range(2, 1000 000):
    if i in numbers:
        steps = numbers[i]
    else:
        n = i
        steps = 0
        found = False

        while not found:
            if n&2 == 0:
                n = n/2
            else:
                n = 3*n + 1
            if n in numbers:
                steps = numbers[n]
                found = True
            else:
                newNumbers.append(n)
        # Store all the new numbers into the dictionary
        for num in newNumbers:
            steps = steps + 1
            numbers[num] = steps
    if steps>max:
        max = steps
        startMax = i
return startMax

You may want to do some testing to find out which one is better, but my bet would be on the first one.

solved Solving Euler #14 with bruteforce in Python [closed]