Last active
December 11, 2015 08:58
-
-
Save zerosum/4576925 to your computer and use it in GitHub Desktop.
Project Euler: Problem 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Euler0004 { | |
def main(args: Array[String]): Unit = { | |
println(findLargiestPalindrome(3)) | |
} | |
private def findLargiestPalindrome(digit: Int): Int = { | |
val minRange = Math.pow(10, digit-1).toInt | |
val maxRange = Math.pow(10, digit).toInt | |
val factors = (minRange until maxRange).toList | |
findLargiestPalindrome(factors, 0) | |
} | |
private def findLargiestPalindrome(factors: List[Int], tempLargiest: Int): Int = { | |
val palindromes = factors.map(_ * factors.last) | |
.filter(x => x.toString == x.toString.reverse) | |
if(Math.pow(factors.init.last, 2) < tempLargiest){ | |
tempLargiest | |
} else if(palindromes.nonEmpty && tempLargiest < palindromes.last){ | |
findLargiestPalindrome(factors.init, palindromes.last) | |
} else { | |
findLargiestPalindrome(factors.init, tempLargiest) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment