Sum All Odd Fibonacci Numbers
What is "Fibonacci Numbers" ? Fibnacci Series wiki↓費氏數列(Fibonacci Series)在數學上是以遞迴的方法來定義: Fib(0) = 1, Fib(1) = 1, Fib(n) = Fib(n-1) + Fib(n-2) if n> 2 用文字來說,就是費波那契數列由0和1開始,之後的費波那契系數就由之前的兩數相加。首幾個費波那契系數是:0, 1, 1, 2, 3, 5, 8, 13,題目要求為: 將奇數項的數字加總
function sumFibs(num) {
var result = 0;
function fibs(n)
{
return (n == 1 || n == 2) ? 1 : fibs(n-1) + fibs(n-2);
}
for(var i=1;i<=num;i++)
{
if(fibs(i) <= num && (fibs(i)%2) == 1 )
result += fibs(i);
}
return result;
}
sumFibs(4);
sumFibs(1000);
sumFibs(4000000);
sumFibs(75025);
Solution 1:
function sumFibs(num) {
var result = 0;
function fibs(n)
{
var temp ;
var x = 1 , y = 1;
for(var i=3;i<=n;i++)
{
temp = x + y;
x = y;
y = temp;
}
return (n == 1 || n == 2) ? 1 : temp;
}
for(var i=1;i<=num;i++)
{
if(fibs(i) <= num && (fibs(i)%2) == 1 )
result += fibs(i);
}
return result;
}
sumFibs(4);
sumFibs(1000);
sumFibs(4000000);
sumFibs(75025);
Solution 2:
P.S. / Reference: about Recursion