Sum of Even Fibonacci Numbers

  • 时间:2020-09-10 12:55:33
  • 分类:网络文摘
  • 阅读:86 次

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) —

推荐阅读:
冬至时节,常吃这几种传统美食可补阳、防寒!  只有这样吃大蒜才能杀菌防癌,以前你吃对了吗  丝瓜营养丰富,其对人体的保健功效如此之多  患有胃病的人常吃这些食物,可以帮助调理好胃  山药营养丰富食疗价值高,助爱美女性吃出好身材  糖尿病患者常有这些饮食误区,朋友们注意啦!  网络上流传甚广的垃圾食品方便面有毒、致癌的传闻是真的吗?  经常吃核桃仁可以补脑是真的吗 一天吃多少核桃才健康  甘蓝汁食疗方法对胃病患者非常有益 疗效甚至超过单纯药物  面部出现这些变化则是男人肾虚要进行饮食调理 
评论列表
添加评论