Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import timeit
- from primefac import primes, primefac, isprime
- "==============================================="
- " Largest palindrome product"
- " Problem 4 "
- " A palindromic number reads the same both ways. "
- " The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. "
- " Find the largest palindrome made from the product of two 3-digit numbers. "
- "==============================================="
- " Solution 1"
- def is_palindrome(n):
- """ReturnTrueifnisapalindrome;Falseotherwise."""
- s = str(n)
- return s == s[::-1]
- def product_lst(n):
- palindrome = max_palindrome = 0
- pair = (0,0)
- for i in xrange(n - 1, 0, -1):
- "Since all palindromes are divisible by 11, either j or i has to be as well"
- if i % 11 == 0:
- j_max = i
- j_range = xrange(i+1, 0, -1)
- else:
- j_max = 11*int(i/11)
- j_range = xrange(j_max, 0, -11)
- if i*j_max < palindrome:
- break
- for j in j_range:
- product = i*j
- if product < palindrome:
- break
- if is_palindrome(product):
- if product > palindrome:
- palindrome = product
- pair = (i, j)
- return (pair, palindrome)
- " Solution 2"
- def palindrome_product(num):
- " Makes a generator that generates palindromes with length num"
- palindrome_generator = generate_palindromes(num)
- for palindrome in palindrome_generator:
- num1, num2 = is_product_of_two(palindrome, num)
- if num1 != 0:
- return ((num1, num2), palindrome)
- def generate_palindromes(n):
- " Generates palindromes of decreasing order"
- first_half = 10**n - 1
- while first_half > 10**(n-1) - 1:
- second_half = str(first_half)[::-1]
- palindrome = int(str(first_half) + str(second_half))
- yield palindrome
- first_half -= 1
- def is_product_of_two(palindrome, n):
- " Checks wheter the palindrome can be written as a product"
- " of two numbers of length num"
- palindrome //= 11
- "All palindromes are divisible by 11"
- num_1 = num_2 = 0
- if not isprime(palindrome):
- " Generate numbers such that 11*i has length n"
- for i in xrange(10**(n)/11, 10**(n-1)/11, -1):
- " If num2 > 10**n then num2 is no longer a n-digit number"
- if palindrome > i*10**n:
- break
- if palindrome % i == 0:
- num_1 = i*11
- num_2 = palindrome/i
- break
- return num_1, num_2
- if __name__ == '__main__':
- # n = 10
- limit = 5
- print product_lst(10**limit)
- print palindrome_product(9)
- # print timeit.timeit(lambda: palindrome_product(8), number = 1)/float(1)
- # print timeit.timeit(lambda: palindrome_product(9), number = 1)/float(1)
Advertisement
Add Comment
Please, Sign In to add comment