Project Euler 5 in Python - How can I optimize my solution?

后端 未结 20 1084
醉梦人生
醉梦人生 2020-11-30 08:00

I\'ve recently been working on Project Euler problems in Python. I am fairly new to Python, and still somewhat new as a programmer.

In any case, I\'ve ran into a sp

20条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 08:49

    I got the solution in 0.066 milliseconds (only 74 spins through a loop) using the following procedure:

    Start with smallest multiple for 1, which = 1. Then find the smallest multiple for the next_number_up. Do this by adding the previous smallest multiple to itself (smallest_multiple = smallest_multiple + prev_prod) until next_number_up % smallest_multiple == 0. At this point smallest_multiple is the correct smallest multiple for next_number_up. Then increment next_number_up and repeat until you reach the desired smallest_multiple (in this case 20 times). I believe this finds the solution in roughly n*log(n) time (though, given the way numbers seem to work, it seems to complete much faster than that usually).

    For example:

    1 is the smallest multiple for 1

    Find smallest multiple for 2

    Check if previous smallest multiple works 1/2 = .5, so no

    previous smallest multiple + previous smallest multiple == 2.

    Check if 2 is divisible by 2 - yes, so 2 is the smallest multiple for 2

    Find smallest multiple for 3

    Check if previous smallest multiple works 2/3 = .667, so no

    previous smallest multiple + previous smallest multiple == 4

    Check if 4 is divisible by 3 - no

    4 + previous smallest multiple == 6

    Check if 6 is divisible by 3 - yes, so 6 is the smallest multiple for 3

    Find smallest multiple for 4

    Check if previous smallest multiple works 6/4 = 1.5, so no

    previous smallest multiple + previous smallest multiple == 12

    Check if 12 is divisble by 4 - yes, so 12 is the smallest multiple for 4

    repeat until 20..

    Below is code in ruby implementing this approach:

    def smallestMultiple(top)
        prod = 1
        counter = 0
        top.times do
            counter += 1
            prevprod = prod
            while prod % counter != 0
                prod = prod + prevprod
            end
        end
        return prod
    end
    

提交回复
热议问题