测试一个数字是否等于2个连续斐波纳契数的乘法

时间:2017-03-08 19:10:25

标签: javascript

以下是指向the challenge的链接。

基本上,任务是测试一个随机传递的数字是否等于2个连续的Fibonacci的乘法。

function productFib(prod) {
    var x = []
    var z;

    var a = 0
    var b = 1
    var c = 7
    var h = 1000
    while (c < 100) {
        var t = a + b
        var a = b
        var b = t
        x.push(t)
        c++
    }
    for (var i = 0; i < h; i++) {
        if (prod = x[i] * x[i + 1]) {
            z = [x[i], x[i + 1], true]
        } else {
            z = [x[i], x[i + 1], false]
        }
    }
    return z
}

首先,我正在创建一个生成Fibonacci数的函数,然后我将它们传递给数组。这是经过测试的,所以我猜问题不存在。然后我尝试创建一个for循环,它将每2个数字相乘,然后检查它们是否等于随机数。

至少这是我的想法,但我每次都会收到类似 - [1, 2, true][undefined]的结果。

1 个答案:

答案 0 :(得分:-1)

此代码有效:

function productFib(prod){
    var x = []
    var z;

    var a = 0
    var b = 1
    var c = 0
    var h = 1000
    var t=0

    //Edited the loop to only check numbers below the one you are looking
    // to make(prod) because any two consecutive numbers over that will not produce the 
    // number you are looking for(14*any number above that cannot make 13)
    while( t < prod){
        //removed c++
        t = a + b
        var a = b
        var b = t
        x.push(t)
   }
   //Set the loop to loop through the whole array(x.length)
   for(var i = 0; i < x.length; i++){
        if(prod == x[i]*x[i+1]){ //Added a double equals sign
            z =[x[i], x[i+1], true]
            //For testing
            console.log(x[i] + ' and '+x[i+1] + ' make ' + prod)

            //Return the number when one is found, not after looking through
            //the whole array
            return z
        }
     }
   //In case none are found
   return false
 }
 productFib(4895) //this is the multiplication of 89 and 55, successive fib's

演示在这里:https://jsfiddle.net/qrq3zh7j/3/

更改详见评论