Scala: Project Euler: Problem 4
November 23rd, 2009
Problem
Find the largest palindrome made from the product of two 3-digit numbers.
object Problem4 {
def main(args : Array[String]) : Unit = {
println(solve(3))
}
def solve(nDigits:Int) : Int = {
val start = Math.pow(10, nDigits).intValue - 1
val end = Math.pow(10, nDigits-1).intValue - 1
val nDigitNumbers = new Range(start, end, -1)
val productPalindromes = for{
n1 <- nDigitNumbers
n2 <- nDigitNumbers
prod = (n1 * n2)
if(isPalindrome(prod))
} yield prod
productPalindromes.reduceLeft(max(_,_))
}
def max(x:Int, y:Int) : Int = if(x > y) x else y
def isPalindrome(x:Int) : Boolean = {
val str = x.toString()
str == str.reverse.toString()
}
}