Euler problem number #4

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

    Here is a solution that you might consider. It could be far more efficient but only takes a little time to run.

    largest = 0
    for a in range(100, 1000):
        for b in range(100, 1000):
            c = a * b
            if str(c) == ''.join(reversed(str(c))):
                largest = max(largest, c)
    print(largest)
    
    0 讨论(0)
  • 2021-01-03 11:48

    Here is an efficient general solution (~5x faster than others I have seen):

    def pgen(factor):
        ''' Generates stream of palindromes smaller than factor**2 
            starting with largest possible palindrome '''
        pmax = str(factor**2)
        half_palindrome = int(pmax[0:len(pmax)/2]) - 1
        for x in xrange(half_palindrome, 0, -1):
            yield int(str(x) + str(x)[::-1])
    
    def biggest(factor):
        ''' Returns largest palindrome and factors '''
        for palindrome in pgen(factor):
            for f1 in xrange(factor/11*11, factor/10, -11):
                f2 = palindrome/f1
                if f2 > factor:
                    break
                if f2*f1 == palindrome:
                    return palindrome, f1, f2
    
    >>> biggest(99)
    (9009, 99, 91)
    >>> biggest(999)
    (906609, 993, 913)
    >>> biggest(9999)
    (99000099, 9999, 9901)
    >>> biggest(99999)
    (9966006699L, 99979, 99681L)
    >>> biggest(9999999)
    (99956644665999L, 9998017, 9997647L)
    >>> biggest(99999999)
    (9999000000009999L, 99999999, 99990001L)
    >>> biggest(999999999)
    (999900665566009999L, 999920317, 999980347L)
    
    0 讨论(0)
提交回复
热议问题