Sunday, 24 September 2023

Solving Project Euler Problem 4: Largest Palindrome Product

 Problem

A palindromic number reads the same forwards and backwards. 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."

Solution

A palindrome is a sequence of characters (or in this case, digits) that reads the same forwards and backwards. Examples of palindromes include "racecar," "level," and "deified." In the context of this problem, we are looking for palindromic numbers.

For example, consider the number 9009. It is a palindrome because it reads the same forwards and backwards. When expressed as the product of two 2-digit numbers (91 and 99), it fulfills the conditions set by the problem.

 

1.      We define a helper function, palindrome_number, which takes a number as input, converts it to a string, and checks if it's the same forwards and backwards.

2.      The largest_palindrome function takes one argument, n, which represents the number of digits in the numbers we want to multiply.

3.      We initialize larg_palindrome to zero and initial to the largest n-digit number (e.g., 999 for n=3).

4.      We use nested loops to iterate through all possible combinations of n-digit numbers, starting from the largest values and moving downwards.

5.      Inside the loops, we calculate the product of a and b.

6.      We check if the product is a palindrome using the palindrome_number function and if it's greater than the current larg_palindrome. If both conditions are met, we update larg_palindrome with the new value.

7.      After the loops finish, larg_palindrome contains the largest palindrome product of two n-digit numbers.

 

Solving Project Euler Problems provides a great opportunity to practice coding and algorithmic thinking.

 

 

 

No comments:

Post a Comment

Solving Project Euler Problem 10: Summation of Primes

  Problem "The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million." Solution ...