生成整数因子的scala方法是什么?这是我的看法1:
def factorize(x: Int): List[Int] = {
def foo(x: Int, a: Int): List[Int] = {
if (a > Math.pow(x, 0.5))
return List(x)
x % a match {
case 0 => a :: foo(x / a, a)
case _ => foo(x, a + 1)
}
}
foo(x, 2)
}
factorize(360)//列表(2,2,2,3,3,5)
根据@ SpiderPig和@ seth-tisue的评论取2
def factorize(x: Int): List[Int] = {
def foo(x: Int, a: Int): List[Int] = {
(a*a < x, x % a) match {
case (true, 0) => a :: foo(x/a, a)
case (true, _) => foo(x, a+1)
case (false, _) => List(x)
}
}
foo(x, 2)
}
答案 0 :(得分:6)
尾递归解决方案:
def factorize(x: Int): List[Int] = {
@tailrec
def foo(x: Int, a: Int = 2, list: List[Int] = Nil): List[Int] = a*a > x match {
case false if x % a == 0 => foo(x / a, a , a :: list)
case false => foo(x , a + 1, list)
case true => x :: list
}
foo(x)
}
答案 1 :(得分:0)
&#34; Take 2&#34;从问题:
def factorize(x: Int): List[Int] = {
def foo(x: Int, a: Int): List[Int] = x % a match {
case _ if a * a > x => List(x)
case 0 => a :: foo(x / a, a)
case _ => foo(x, a + 1)
}
foo(x, 2)
}
此外,以下方法可能会更快一些(在上一次迭代中没有x % a
计算):
def factorize(x: Int): List[Int] = {
def foo(x: Int, a: Int): List[Int] = if (a * a > x) List(x) else
x % a match {
case 0 => a :: foo(x / a, a)
case _ => foo(x, a + 1)
}
foo(x, 2)
}