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

后端 未结 20 1115
醉梦人生
醉梦人生 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:57

    How about this? The required number is, after all, the LCM of the given numbers.

    def lcm(a,b):
    lcm1 = 0
    if a == b:
        lcm1 = a
    else:
        if a > b:
            greater = a
        else:
            greater = b
        while True:
            if greater % a == 0 and greater % b == 0:
                lcm1 = greater
                break
            greater += 1
    
    return lcm1            
    
    
    import time
    start_time = time.time()
    
    list_numbers = list(range(2,21))
    
    lcm1 = lcm(list_numbers[0],list_numbers[1])
    
    for i in range(2,len(list_numbers)):
        lcm1 = lcm(lcm1,list_numbers[i])
    
    print(lcm1)
    print('%0.5f'%(time.time()-start_time))
    

    This code took a full 45 s to get the answer to the actual question! Hope it helps.

提交回复
热议问题