应用斐波那契数列,处理大数

Applying Fibonacci, working with large numbers

我正在尝试在 Rosalind 页面上成功完成 this challenge。挑战是:

Given: Positive integers n≤40 and k≤5.

Return: The total number of rabbit pairs that will be present after n months if we begin with 1 pair and in each generation, every pair of reproduction-age rabbits produces a litter of k rabbit pairs (instead of only 1 pair).

练习给出了一个包含两个数字的文本文件,即上面提到的nk

我的代码尝试实现 Fibonacci,在较少的月份内按预期工作。然而,随着月份数的增加,结果开始变得非常大,在每种情况下,我的答案都是 Infinity.

我的公式应用不正确吗?还是 Javascript 用于此类练习的语言选择不当?

我的代码:

function fibonacciRabbits(months, pairs){
    
    var months = months;
    var numberOfPairs = pairs;
    var result = 0;
    
    // Declare parent & child arrays with constants
    var parentArr = [1, numberOfPairs + 1]
    var childArr = [numberOfPairs, numberOfPairs]
    
    var total = []
    
    // Loop from the point after constants set above
    for(var i = 2; i < months - 2 ; i++){
        parentArr.push(parentArr[i-1] + childArr[i-1])
        childArr.push(parentArr[i-1] * childArr[i-2])    
        total.push(parentArr[i-1] + childArr[i-1])
    }
    
    result = childArr[childArr.length - 1] + parentArr[parentArr.length - 1]
    
    console.log(months + ' months and ' + numberOfPairs + ' pairs:\n')
    console.log('parentArr:\n', parentArr)
    console.log('childArr:\n', childArr)
    console.log('total\n', total)
    console.log('result:', result)
    console.log('\n\n\n')
}

fibonacciRabbits(5, 3)
fibonacciRabbits(11, 3)
fibonacciRabbits(21, 3)
fibonacciRabbits(31, 2)

这里是 REPL

这是一个更简短的解决方案,它不会产生如此大的数字,并且可以处理最大情况而不会在 Javascript 中达到无穷大。我认为您的解决方案变得太大太快了。

function fibonacciRabbits(months, reproAmount){

    var existingAdults = 0;
    var adultPairs = 0;
    var childPairs = 1;

    for(var i = 2; i <= months; i++){
        adultPairs = childPairs;       //children mature
        childPairs = (existingAdults * reproAmount);  //last month's adults reproduce
        existingAdults += adultPairs;  //new adults added to the reproduction pool
    }

    console.log(existingAdults + childPairs);
}

为确保您走在正确的轨道上,请使用以下方法测试您的功能:

fibonacciRabbits(1, 1);
fibonacciRabbits(2, 1);

网站上说:f(1)=f(2)=1。所以无论如何这些都应该产生“1”。您的代码为这两个生成“3”。