所以我最近发现了这个网站(https://projecteuler.net)。第二个问题要求你找到所有偶数斐波纳契数不到四百万的总和。我试图用我有限的JavaScript为我解决这个问题,但它似乎根本没有用。这是jsfiddle:http://jsfiddle.net/ophunt/pnf24j7q/3/
以下是其中包含的javascript:
//variables here
var sum = 0;
var fibA = 1;
var fibB = 1;
var store = 0;
//main loop
while (fibA < 4000000) {
store = fibA;
fibA += fibB;
fibB = store;
if (fibA % 2 === 0) {
sum += fibA;
}
}
Document.getElementById("result").innerHTML = sum;
答案 0 :(得分:1)
所以有一些事情可以帮到你:
斐波那契(n)=斐波那契(n + 2)-1的总和 这很好,因为您不必手动执行总和,因为您在创建序列时已经在执行总和
甚至斐波那契数也是每三个斐波纳契数。这最终意味着均衡的总和等于所有的总和除以2。
例如:
fibs: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
sums: 1, 2, 4, 7, 12, 20, 33, 54, 88
even_sum: 0, 0, 2, 2, 2, 10, 10, 10, 44
javascript implimentation看起来像这样:
var findFibNum = function(num) {
var est = Math.log(num * Math.sqrt(5)) /(Math.log((Math.sqrt(5)+1)/2))
return Math.floor(est)
}
了解这三件事可以快速解决问题:
var top = 4000000;
/* function finds nth fibonacci number */
var fib = function(n){
if (n <=1) return n;
return fib(n-1) + fib(n-2);
}
/* given a number this finds closest n below it i.e. for 34 it give 9
because 34 is the nineth fibonacci number
*/
var findFibNum = function(num) {
var est = Math.log(num * Math.sqrt(5)) /(Math.log((Math.sqrt(5)+1)/2))
return Math.floor(est)
}
var n = findFibNum(top) /* fib(n) is the largest fibonacci below top */
/* the sum of fibonacci number n is fib(n)+2 -1 -- this beats looping and adding*/
var fibsum = fib(n+2) -1
/* it s a nice feature of the sequence that the sum of evens is equal to the sum off all dived by 2 */
var evensum = fibsum/2
Fiddle给出4613732