【发布时间】: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