highest palindrome with 3 digit numbers in python

后端 未结 13 1203
梦如初夏
梦如初夏 2021-02-01 10:35

In problem 4 from http://projecteuler.net/ it says:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-d

相关标签:
13条回答
  • 2021-02-01 11:12

    580085 = 995 X 583, where 906609 = 993 X 913. Found it only by applying brute-forcing from top to bottom!

    0 讨论(0)
  • 2021-02-01 11:13

    Simple:

    def is_pallindrome(n):
        s = str(n)
        for n in xrange(1, len(s)/2 + 1):
            if s[n-1] != s[-n]:
                return False    
        return True
    
    largest = 0
    for j in xrange(100, 1000):
        for k in xrange(j, 1000):
            if is_pallindrome(j*k):
                if (j*k) > largest: largest = j*k
    print largest
    
    0 讨论(0)
  • 2021-02-01 11:17

    Here is my Python code:

    max_pal = 0
    for i in range(100,999):
        for j in range(100,999):
          mult = i * j 
          if str(mult) == str(mult)[::-1]: #Check if the number is palindrome
              if mult > max_pal: 
                  max_pal = mult
    print (max_pal)
    
    0 讨论(0)
  • 2021-02-01 11:22

    ReThink: efficiency and performance

    def palindrome(n):    
    
        maxNumberWithNDigits = int('9' * n) #find the max number with n digits
    
        product = maxNumberWithNDigits * maxNumberWithNDigits 
    
        #Since we are looking the max, stop on the first match
    
        while True:        
            if str(product) == str(product)[::-1]: break;
    
            product-=1
    
        return product
    
    start=time.time()
    palindrome(3)
    end=time.time()-start
    

    palindrome...: 997799, 0.000138998031616 secs

    0 讨论(0)
  • 2021-02-01 11:25

    Here I added two 'break' to improve the speed of this program.

    def is_palindrome(num):
        return str(num) == str(num)[::-1]
    def max_palindrome(n):
        max_palindrome = 1
        for i in range(10**n-1,10**(n-1)-1,-1):
            for j in range(10**n-1,i-1,-1):
                if is_palindrome(i*j) and i*j > max_palindrome:
                    max_palindrome = i * j
                    break
                elif i*j < max_palindrome:
                    break
        return max_palindrome
    n=int(raw_input())
    print max_palindrome(n)
    
    0 讨论(0)
  • 2021-02-01 11:25

    Here is my code to solve this problem.

    lst = []
    for i in range(100,1000): 
        for n in range(2,i) : 
            lst.append (i* n) 
            lst.append(i*i)
    
    lst2=[]
    for i in lst: 
        if str(i) == str(i)[::-1]:
            lst2.append(i)
    print max(lst2) 
    
    0 讨论(0)
提交回复
热议问题