我嘗試完成使用JavaScript codewars一個卡塔,這些都是說明:遞歸函數輸出怪異值
The Fibonacci numbers are the numbers in the following integer sequence (Fn): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... such as F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying F(n) * F(n+1) = prod. Your function productFib takes an integer (prod) and returns an array: [F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True) depending on the language if F(n) * F(n+1) = prod. If you don't find two consecutive F(m) verifying F(m) * F(m+1) = prod you will return [F(m), F(m+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False) F(m) being the smallest one such as F(m) * F(m+1) > prod. Examples productFib(714) # should return [21, 34, true], # since F(8) = 21, F(9) = 34 and 714 = 21 * 34 productFib(800) # should return [34, 55, false], # since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 3
好,我只需要創建一個斐波那契數列,並返回數組,這裏是我的代碼:
function productFib(prod) {
return fib(0, 1, prod);
}
function fib(a, b, prod) {
if (a * b < prod) {
return (a + b) + fib(b, a + b, prod);
}
else if (a * b == prod) {
return [a, b, true];
}
else {
return [a, b, false];
}
}
它是一個遞歸斐波那契數列,怎麼過,當我運行它,我沒有得到預期的陣列,其結果是對的,變量具有正確的價值,而是返回數組的時候,我收到了非常長的第一個元素,它看起來像包含整個斐波那契系列。 下面是測試情況:
productFib(4895)
"12358132134558955,89,true"
你們可以給我解釋一下什麼是對那裏發生的:(productFib(4895), [55, 89, true])
,如果我與測試,我得到以下運行我的代碼?
'FIB()'有時返回一個數組,作爲用於'+',將其轉換成字符串的操作數,其最終。 – 2017-04-04 16:49:06