Euler problem number #4

前端 未结 14 1992
萌比男神i
萌比男神i 2021-01-03 11:00

Using Python, I am trying to solve problem #4 of the Project Euler problems. Can someone please tell me what I am doing incorrectly? The problem is to Find the larg

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 11:25

    If your program is running slow, and you have nested loops like this:

    for z in range(100, 1000):
        for y in range(100, 1000):
            for x in range(1, 1000000):
    

    Then a question you should ask yourself is: "How many times will the body of the innermost loop execute?" (the body of your innermost loop is the code that starts with: x = str(x))

    In this case, it's easy to figure out. The outer loop will execute 900 times. For each iteration the middle loop will also execute 900 times – that makes 900×900, or 810,000, times. Then, for each of those 810,000 iterations, the inner loop will itself execute 999,999 times. I think I need a long to calculate that:

    >>> 900*900*999999
    809999190000L
    

    In other words, you're doing your palindrome check almost 810 billion times. If you want to make it into the Project Euler recommended limit of 1 minute per problem, you might want to optimise a little :-) (see David's comment)

提交回复
热议问题