Given an integer 1 ≤ n ≤ 40 , it is necessary to calculate the n- th Fibonacci number (recall that F [0] = 0, F [1] = 1 and Fn = Fn − 1 + Fn − 2 for n ≥ 2 ).
Sample Input:
3Sample Output:
2
I tried to implement this:
function fib(n) { if (n < 1 || n > 40) return 1; var a = [0, 1]; for (var i = 2; i <= n; i++) { a.push(a[i - 1] + a[i - 2]); } return a[n]; } If you fill the array with Fibonacci numbers by the same condition, it is obtained as follows:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155] But this decision is why wrong. Tell me where I made a mistake. Task taken from Stepic.org.
function fib(n) var a = [0,1,1,2 ...]; return a[n];function fib(n) var a = [0,1,1,2 ...]; return a[n];- pavela[20]I get6765, but I should -10946. - Amandi