2017-04-04 73 views
0

我尝试完成使用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])

,如果我与测试,我得到以下运行我的代码?

+0

'FIB()'有时返回一个数组,作为用于'+',将其转换成字符串的操作数,其最终。 – 2017-04-04 16:49:06

回答

0

fib functon有它返回一个非数组值的一个案件:

return (a + b) + fib(b, a+b, prod); 

...和两种情况下,它返回一个参照的数组:

return [a,b,true]; 
// and 
return [a,b,false]; 

即第一个使用在+操作的返回值。这会将数组强制转换为一个字符串,该字符串会生成以逗号分隔的转换为字符串的条目列表,然后进行字符串连接。

您可能不想在该return中执行字符串连接。简单地将其改为return fib(b, a + b, prod);似乎解决该问题:

function productFib(prod) { 
 
    return fib(0, 1, prod); 
 
} 
 

 
function fib(a, b, prod) { 
 
    if (a * b < prod) { 
 
    return fib(b, a + b, prod); 
 
    } else if (a * b == prod) { 
 
    return [a, b, true]; 
 
    } else { 
 
    return [a, b, false]; 
 
    } 
 
} 
 
console.log(productFib(4895)); // [55, 89, true]

+0

这将解决奇怪的输出,但代码仍然是错误的 - 他必须在他回过头时“回滚”。他的代码不这样做。不过我给了+1,因为这是OP不理解的大问题。 – Hogan

+0

@Hogan:如果你想进一步回答这个问题,我已经发布了社区维基...... :-)(我保证你对斐波那契系列的了解比我多......) –

+0

其实我认为这是正确的,因为我只是重新阅读要求,他希望第一个等于或大于 - 这是...由于某种原因,我想等于或小于。 – Hogan

2

只需从返回的值删除(a + b) +

更换

return (a + b) + fib(b, a+b, prod); 

return fib(b, a+b, prod); 
+1

没有“为什么”,“什么”才是如此有用。 –

+0

我同意,这不是最好的答案,我必须管理我专注于快速提供帮助,因为我知道在做卡塔时不发现错误是多么令人沮丧。 –