【发布时间】:2018-10-04 21:11:36
【问题描述】:
我最近开始学习 scala,发现了一个有趣的任务。挑战在于找到最大的回文数(例如 144858441),它是两个 5 位素数的乘积。此外,我还需要返回两个乘数。我是这样解决的:
case class PrimesHolder(a:Int, b:Int, palindrome:BigInt)
object palindromeFinder {
def find(from:Int, to:Int) = {
// getting all primes between FROM and TO
val primes = calculatePrimesStreamBetween(from, to)
// getting all possible compositions of primes and filtering non-palindromes,
// result is a list of tuples (BigInt, Int), first val is palindrome, second is one of prime multipliers (we'll get the second one by division)
val palindromes = multiplyAll(primes).filter(palindromeFilter)
// looking for maximum
val res = if (palindromes.nonEmpty) palindromes.maxBy(_._1) else (BigInt(0), 0)
// return statement
if (res._2 != 0) PrimesHolder(res._2, (res._1 / res._2).toInt, res._1) else PrimesHolder(0, 0, 0)
}
// it's The Sieve Eratosthen implementation
private def calculatePrimesStreamBetween(from:Int, to: Int): List[Int] = {
val odds = Stream.from(3, 2).takeWhile(_ <= Math.sqrt(to).toInt)
val composites = odds.flatMap(i => Stream.from(i * i, 2 * i).takeWhile(_ <= to))
Stream.from(3, 2).takeWhile(i => i >= from && i <= to).diff(composites).toList
}
// multiplies values in lists "each by each", yields list of tuples (BigInt, Int)
private def multiplyAll(a:List[Int]) = a.flatMap(item => a.filter(j => j >= item).map(i => (BigInt(i) * item, i)))
// palindrome filter function for passing to .filter((BigInt, Int) => Boolean)
private def palindromeFilter(num:(BigInt, Int)):Boolean = {
if (num._1.toString.head != num._1.toString.last) false else num._1.toString == num._1.toString.reverse
}
}
/////////////////////////////////////////////////////////
object Main {
def main(args: Array[String]): Unit = {
val res = palindromeFinder.find(10000, 99999)
println(s"${res.palindrome} = ${res.a} * ${res.b}")
}
}
但是这段代码需要太多内存,在我的电脑上需要大约 30 秒。 为了得到结果,我需要在执行前输入 -J-Xms1024m -J-Xmx3000m 参数。 如何以功能方式优化我的代码? 谢谢!
【问题讨论】:
-
你做了什么仪器?例如,有多少个 5 位素数 (
n)?您将需要n x n/2乘法和n x n/2测试回文罩。
标签: algorithm scala optimization collections functional-programming