Advertisement
Woobinda

largest palindrome of two 3-digit numbers

Dec 2nd, 2016
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. """First variant"""
  2.  
  3. def is_palindrome(number):
  4.     """Returns True if the number is a palindrome,
  5.     else False.
  6.     """
  7.     return str(number) == str(number)[::-1]
  8.  
  9.  
  10. def largest_palindrome(max_number, min_number):
  11.     """check the results of multiplication of numbers in a predetermined range
  12.     and returns the largest palindrome
  13.     """
  14.     largest_palindrome = 0
  15.     for i in range(max_number, min_number, -1):
  16.         for k in range(max_number, min_number, -1):
  17.             product = i * k
  18.             if product > largest_palindrome and is_palindrome(product):
  19.                 largest_palindrome = product
  20.     return largest_palindrome
  21.  
  22. print(largest_palindrome(999, 99))
  23.  
  24.  
  25. """Second Variant with optimisation"""
  26.  
  27. def make_palindrome(number):
  28.     """
  29.    Make palindrome from number
  30.    """
  31.     palindrome = int(str(number) + str(number)[::-1])
  32.     return palindrome
  33.  
  34.  
  35. def largest_palindrome():
  36.     """Check the possible palindromes for numbers in descending order
  37.    and returns the first satisfying palindrome.
  38.    """
  39.     largest_possible_number = 999 * 999   # 998001 and it's not a palindrome
  40.     first_half = int(str(largest_possible_number)[:-3])   # 998
  41.     for number in range(first_half, 99, -1):   # make possible palindrome in descending order and check it
  42.             for i in range(999, 99, -1):
  43.                 palindrome = make_palindrome(number)
  44.                 if palindrome / i > 999 and i * i < palindrome:
  45.                     break
  46.                 if palindrome % i == 0:   # if a palindrome satisfies all the conditions - return
  47.                     return palindrome
  48.  
  49. print(largest_palindrome())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement