Euler problem number #4

前端 未结 14 1871
萌比男神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:23

    Wow, this approach improves quite a bit over other implementations on this page, including mine.

    Instead of

    • walking down the three-digit factors row by row (first do all y for x = 999, then all y for x = 998, etc.),

    we

    • walk down the diagonals: first do all x, y such that x + y = 999 + 999; then do all x, y such that x + y = 999 + 998; etc.

    It's not hard to prove that on each diagonal, the closer x and y are to each other, the higher the product. So we can start from the middle, x = y (or x = y + 1 for odd diagonals) and still do the same short-circuit optimizations as before. And because we can start from the highest diagonals, which are the shortest ones, we are likely to find the highest qualifying palindrome much sooner.

    maxFactor = 999
    minFactor = 100
    
    def biggest():
        big_x, big_y, max_seen, prod = 0, 0, 0, 0
    
        for r in xrange(maxFactor, minFactor-1, -1):
            if r * r < max_seen: break
    
            # Iterate along diagonals ("ribs"):
    
            # Do rib x + y = r + r
            for i in xrange(0, maxFactor - r + 1):
                prod = (r + i) * (r - i)
    
                if prod < max_seen: break
    
                if is_palindrome(prod):
                    big_x, big_y, max_seen = r+i, r-i, prod
    
            # Do rib x + y = r + r - 1
            for i in xrange(0, maxFactor - r + 1):
                prod = (r + i) * (r - i - 1)
    
                if prod < max_seen: break
    
                if is_palindrome(prod):
                    big_x, big_y, max_seen = r+i,r-i-1, prod
    
        return big_x, big_y, max_seen
    
    # biggest()
    # (993, 913, 906609)
    

    A factor-of-almost-3 improvement

    Instead of calling is_palindrome() 6124 times, we now only call it 2228 times. And the total accumulated time has gone from about 23 msec down to about 9!

    I'm still wondering if there is a perfectly linear (O(n)) way to generate a list of products of two sets of numbers in descending order. But I'm pretty happy with the above algorithm.

提交回复
热议问题