Problem: Find the largest palindrome made from the product of two 3-digit numbers.
Solution: [Spoiler Ahead]
The initial algorithm to the problem is : Check all products of two 3-digit number and store the required number.
Toggle Code
function reverse(n)
reversed = 0
while n > 0
reversed = 10*reversed + n mod 10
n = n/10
return reversed
function isPalindrome(n)
return n = reverse(n)
largestPalindrome = 0
a = 100
while a <= 999
b = 100
while b <= 999
if isPalindrome(a*b) and a*b > largestPalindrome
largestPalindrome = a*b
b = b+1
a = a+1
output largestPalindrome
reversed = 0
while n > 0
reversed = 10*reversed + n mod 10
n = n/10
return reversed
function isPalindrome(n)
return n = reverse(n)
largestPalindrome = 0
a = 100
while a <= 999
b = 100
while b <= 999
if isPalindrome(a*b) and a*b > largestPalindrome
largestPalindrome = a*b
b = b+1
a = a+1
output largestPalindrome
This works quiet well but if you observe we are computing the same product twice. So beginning the value of 'b' from the value of 'a' will suffice for this. Also running the loop in reverse order will speed up the algo as lower number need not be checked for the palindrome case as shown in below implementation:
largestPalindrome = 0
a = 999
while a >= 100
b = 999
while b >= a
if a*b <= largestPalindrome
break
if isPalindrome(a*b)
largestPalindrome = a*b
b = b-1
a = a-1
output largestPalindrome
Thus giving us answer in few seconds !!!
Enjoy coding :-)
No comments:
Post a Comment