【问题标题】:Optimisation algorithms with huge collections with huge numbers (in a functional way)具有大量集合的优化算法(以功能方式)
【发布时间】: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


【解决方案1】:

juvian 给出了一个很好的答案,概述了一些算法策略。以下是其中一些想法,但在 scala 中实现,纯粹是功能性的:

def primes(min: Int, max: Int): List[Int] = {
  val primeCandidates = 2 #:: Stream.from(3, 2)
  def isPrime(n: Int): Boolean = {
    primeCandidates.takeWhile(x => x * x <= n).forall(x => n % x != 0)
  }
  primeCandidates.dropWhile(_ < min).takeWhile(_ < max).filter(isPrime).toList
}

@scala.annotation.tailrec
final def findLargestPalindrome(primesDesc: List[Int], bestSoFar: Option[(Int, Int, Long)]): Option[(Int, Int, Long)] = primesDesc match {
  case p1 :: rest => {
    val needToCheck = bestSoFar match {
      case Some((_, _, product)) => rest.takeWhile(_.toLong * p1 > product)
      case None => rest
    }
    val result = needToCheck.find { p2 =>
      val product = p1.toLong * p2
      val str = product.toString
      str == str.reverse
    }
    val newBest = result.map(p2 => (p1, p2, p1.toLong * p2)).orElse(bestSoFar)
    findLargestPalindrome(rest, newBest)
  }
  case Nil => bestSoFar
}

val primesDesc = primes(10000, 100000).reverse
findLargestPalindrome(primesDesc, None)

我认为在findLargestPalindrome 内我可能重做了太多次乘法,所以你可以考虑收紧它,但实际上它还是很快的。

它找到 33211 * 30109 = 999949999,由于它需要是奇数位数,因此它似乎极有可能是正确的。

【讨论】:

  • 似乎我给出的结果是错误的,因为我复制的 isPalindrome 函数给出了错误的结果,感谢 999949999 的回答 ^^
  • 是的,999949999 是正确答案。感谢这个算法,当我在 REPL 中试用它时,它的运行速度比我的快,我会仔细考虑那里发生了什么
【解决方案2】:

我不知道 scala,但这里有一些提示:

  • 答案的位数必须是奇数。这是因为如果答案的位数为偶数,则它可以被 11 整除。由于您永远不会生成以 11 为因子的数字,因此答案的位数必须为奇数 (9)。
  • 筛子不是必需的,范围很小,数字很小,标准方法应该足以在 1 秒内找到该范围内的所有 8363 个素数。
  • 我们最多需要做8363 * 8363 乘法,这还不错,但最昂贵的部分是检查乘法是否是回文。我们需要尽量减少这些检查。
  • 对于每个素数,如果您将其与其他素数按降序相乘,则您找到的第一个回文将是该素数可能的最高回文数,因此无需迭代其余部分
  • 如果乘法低于找到的最高回文,则无需检查是否为回文

不确定这些技巧中有多少可以以函数式的方式应用到代码中,但这里有一个 javascript 非函数式的方法,它充分利用了这些想法并且花费了不到 1 秒的时间:

var start = new Date().getTime();

function isPrime(n) {
    if (n % 2 == 0) return false;
    for (var i = 3; i <= Math.sqrt(n); i += 2) {
        if (n % i == 0) return false;
    }
    return true;
}

var primes = []

for (var i = 99999; i >= 10000; i--) {
    if (isPrime(i)) primes.push(i)
}

var max = 0;

const isPalindrome = (string) => string == string.split('').reverse().join('');

var max = 0;

for (var i = 0; i < primes.length; i++) {
    var prime1 = primes[i];
    for (var j = i; j < primes.length; j++) {
        var prime2 = primes[j];
        var mul = prime1 * prime2
        if (mul > 999999999) continue;
        if (max > mul) break;
        if (isPalindrome(mul.toString())) {
            max = mul;
        }
    }
}


console.log(max, "took " + (new Date().getTime() - start) + " ms");

附加提示:可以通过使用二分搜索计算第一个 prime2 来进一步优化,这将导致 prime1 有 9 位而不是 10,这样就可以跳过 primes2 的大量迭代

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多