我试图创建一个函数来确定Scala中的数字是否是斐波纳契数。有人可以看看我的代码,让我知道我错过了什么?感谢
def isFibNumber(n: Int): Boolean = {
var fib1 = 0;
var fib2 = 1;
do {
var saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}
答案 0 :(得分:2)
def isFibonacciNumber(n: Int): Boolean = {
var fib1 = -1;
var fib2 = 1;
var res = 0;
do {
res = fib1+fib2;
fib1 = fib2;
fib2 = res;
} while (res < n);
if (res == n)
return true;
else
return false;
}
这应该有效。您的算法中有错误。
答案 1 :(得分:2)
那会有所帮助。无需循环
http://www.geeksforgeeks.org/check-number-fibonacci-number/
object Fib {
def isPerfectSq(n: Int): Boolean = {
val res = math.round(math.sqrt(n))
res * res == n.toLong
}
def isFibonacci(n: Int) = {
isPerfectSq(5 * n * n - 4) || isPerfectSq(5 * n * n + 4)
}
}