Sum all Odd Fibonacci Numbers
1. Requirements
- To a positive integer num, returns the sum of the Fibonacci Ponacic numbers less than or equal to Num.
- The first few numbers in the Fibonacci sequence are 1, 1, 2, 3, 5, and 8, and each subsequent number is the sum of the first two digits.
- It is not possible to implement the Fibonacci sequence with a recursive return. Because memory overflows when NUM is large, it is recommended to use an array to implement it.
2. Ideas
- Using a For loop to derive the first 100 numbers of Fibonacci numbers arr
- Use. Filter () to present all the odd numbers in arr sequentially
- Calculates the sum of the Fibonacci Ponacic numbers less than or equal to num with a for loop
3. Code
function sumFibs(num) { var arr=[1,1]; var sum=0; for (var i=2;i<100;i++){ arr[i]=arr[i-2]+arr[i-1]; } arr=arr.filter(function(val){ return val%2 ===1; }); for(var j=0;arr[j]<=num;j++){ sum +=arr[j]; } return sum;}sumFibs(3);
4. RELATED LINKS
- Http://www.cnblogs.com/meteoric_cry/archive/2010/11/29/1891241.html
Sum all ODD Fibonacci numbers-freecodecamp algorithm Topic