【问题标题】:Need help to check scala code can be made concise. Find all factors of n需要帮助检查 scala 代码可以做得简明扼要。找出 n 的所有因数
【发布时间】:2021-04-13 14:28:48
【问题描述】:

下面的实现是使用scala找到给定'n'的所有因素。这个scala代码可以简洁吗?请注意,下面的代码有 O(sqrt(n))。

    @scala.annotation.tailrec
    def helper(n: Int, current: Int, acc: List[Int]): List[Int] = {
      if (current > math.sqrt(n)) acc
      else if (n % current == 0) {
        val a = n / current
        val b = n / a
        helper(n, current + 1, acc :+ a :+ b)
      } else helper(n, current + 1, acc)
    }

    helper(A, 1, List.empty[Int]).sorted.toArray

我不是在寻找以下解决方案,因为这是 O(n) 解决方案。

   def factors(n: Int): List[Int] = {
     (1 to n).filter(n % _ == 0)
   }

【问题讨论】:

  • 这对我来说已经够简洁了,但你可以看看 LazyList 上的 unfold 方法。
  • 以下代码可读吗? (for(i <- 1 to math.sqrt(A).toInt if A % i == 0) yield {(i, A / i)}) .flatMap(t => List(t._1, t._2)).sorted.distinct.toArray
  • 由于您的代码已经可以使用,请考虑在Code Review 上提问(但请先查看他们的网站指南)。
  • 另外,不要附加到List,而是尝试附加到它。如果你不想按那个顺序,你可以在最后反转它。
  • 当然。谢谢@用户。我同意。我将在 Code Review 上发布此内容

标签: scala functional-programming factors


【解决方案1】:
 def factors(n: Int): List[Int] = {
     (1 to n).filter(n % _ == 0)
   } 

确实是 O(n)。

但是

def factors(n: Int) = 
  (1 to sqrt(n).toInt).filter(n % _ == 0).flatMap { k => Seq(k, n/k) } 

是 O(sqrt(n)) :)

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多