我一直在研究scala递归问题。我以前使用循环来开发程序,然后使用递归的概念在递归解决方案中转换现有的循环问题。因此,我编写了以下代码以使用循环找到理想的数字。
def isPerfect(n: Int): Boolean = {
var sum = 1
// Find all divisors and add them
var i = 2
while ( {
i * i <= n
}) {
if (n % i == 0) if (i * i != n) sum = sum + i + n / i
else sum = sum + i
i += 1
}
// If sum of divisors is equal to
// n, then n is a perfect number
if (sum == n && n != 1) return true
false
}
这里是我尝试将其转换为递归解决方案的尝试。但是我得到的结果不正确。
def isPerfect(n: Int): Boolean = {
var sum = 1
// Find all divisors and add them
var i = 2
def loop(i:Int, n:Int): Any ={
if(n%i == 0) if (i * i != n) return sum + i + n / i
else
return loop(i+1, sum+i)
}
val sum_ = loop(2, n)
// If sum of divisors is equal to
// n, then n is a perfect number
if (sum_ == n && n != 1) return true
false
}
先谢谢您。
这里是尾递归解
def isPerfectNumber(n: Int): Boolean = {
@tailrec def loop(d: Int, acc: List[Int]): List[Int] = {
if (d == 1) 1 :: acc
else if (n % d == 0) loop(d-1, d :: acc)
else loop(d -1, acc)
}
loop(n-1, Nil).sum == n
}
作为旁注,具有副作用的功能,例如范围限定为[[局部]的状态突变],只要该突变在外部不可见,则仍被视为纯函数,因此在此类函数中使用while循环可能是可以接受的。