Problem
This problem comes from Project Euler 4
Problem
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is .
Find the largest palindrome made from the product of two 3-digit numbers.
Solution
The solution here may not be the most efficient, but it works.
The program loops through all 3-digit number products, converts them to a string, reverses the string, and then checks if the reversed and unreversed strings are equivalent. We convert the numbers to strings, as reversing strings is easier than reversing numbers.
If the product is palindromic, we check to see if it is larger than the current max
palindrome, and if it is, store it.
# Project Euler: Problem 4
# Largest Palindrome Product
max = 0
for num1 in range(100, 1000):
for num2 in range(num1, 1000):
product = num1*num2
if (str(product) == str(product)[::-1]):
if (product > max):
max = product
print(max)
// Project Euler: Problem 4
// Largest Palindrome Product
// Alternate Rust version
fn main() {
let mut max = 0;
for a in 100..1000 {
for b in a..1000 {
let product = a*b;
let f_string: String = format!("{}", product);
let r_string: String = f_string.chars().rev().collect();
if f_string == r_string && product > max {
max = product;
}
}
}
println!("{}", max);
}
Note 1
num2
’s range is between num1
and 1000 to avoid repeated calculations. For example, is the same as and would be an unnecessary calculation. This avoids that problem by setting num2
’s bottom range to num1
.
Note 2
The code [::-1]
reverses the string, allowing us to check if the product
is a palindrome.
str(product) == str(product)[::-1]