// you’re reading...

Project Euler Solutions

Project Euler Problem 4 Solution

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Problem Description

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Analysis

The most efficient way to find the largest palindrome product of two 3-digit numbers is by searching odd factors downwards from 999. We test each product as a palindrome and save it. Our search ends when the next product falls below the largest palindrome found.

For a product to qualify as a palindrome the first and last digit must be the same. In this case it will always be 9, an odd number that can only be derived by the multiplication of two odd numbers.

Solution

Runs < 1 second in Python.

def is_palindromic(n): return str(n)==str(n)[::-1]
 
p=0
for i in range(999, 101, -2):
  for j in range(i, 101, -2):
    if i*j < p: break
    if is_palindromic(i*j): p = i*j
print "Answer to PE4 = ",p

Comments

Search took 3,072 iterations.
The largest palindrome for some other cases: 4 digits: 9999 × 9901 = 99000099, 5 digits: 99979 × 99681 = 9966006699, 6 digits: 999999 × 999001 = 999000000999, 7 digits: 9997647 × 9998017 = 99956644665999

Discussion

No comments for “Project Euler Problem 4 Solution”

Post a comment