Sum of Even Fibonacci Numbers
- Time:2020-09-10 12:55:33
- Class:Weblog
- Read:35
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Javascript Function to Compute the Sum of Even Fibonacci Numbers
Fibonacci Numbers can be computed iterated. Then we need to pick those even Fibonacci numbers. The following is a Javascript function to sum up the Fibonacci numbers less than a maximum value.
The time complexity is obvious O(N) for a iterative Fiboancci sequence where N is the number of Fiboancci numbers less than the threshold. The space complexity is O(1) constant.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function SumOfFibLessThan(max) { let a = 1, b = 2; let sum = 0; while (a <= max) { if (a % 2 === 0) { sum += a; } let c = a + b; a = b; b = c; } return sum; } console.log(SumOfFibLessThan(4000000)); |
function SumOfFibLessThan(max) { let a = 1, b = 2; let sum = 0; while (a <= max) { if (a % 2 === 0) { sum += a; } let c = a + b; a = b; b = c; } return sum; } console.log(SumOfFibLessThan(4000000));
Answer is: 4613732.
–EOF (The Ultimate Computing & Technology Blog) —
Recommend:6 Tips For Doing Taxes as a Freelancer
10 Tips on Recording Video Like a Pro With Your Smartphone
Common Mistakes You Make Before Uploading a WordPress Blog Post
How to Leverage Expert Roundups to Earn High-Quality Links For Y
What Is Color Theory and Why Bloggers Should Know the Basics
5 Ways to Make Sure You Get Paid as an Online Freelancer
Creating a Social Media Contest Strategy to Boost Engagement
A Productivity & Health Guide for Home-Based Entrepreneurs
Recursive Depth First Search Algorithm to Delete Leaves With a G
Algorithms to Determine a Palindrome Number
- Comment list
-
- Comment add