我只能求和10。不能正确。 我得到的是10位数字的总和(仅过滤7位奇数后)。我应该在哪里<= num?
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
预期输出10,但得到99
答案 0 :(得分:3)
将a < num
添加到过滤器回调测试中,以便获得a % 2 && a < num
function sumFibs(num) {
var fib = [0, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function (a) {
return a % 2 && a < num;
}).reduce(function (a, z) {
return a + z;
}, 0);
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
如果只需要这些数字的总和,就不需要使用数组
function sumFibs(num) {
if(num <= 1) return 0;
var a = 0, b = 1, sum = a + b;
while(true) {
var next = a + b;
if(next >= num) {
break;
}
if(next % 2) {
sum += next;
}
a = b;
b = next;
}
return sum
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
答案 1 :(得分:0)
您需要更改循环条件。循环直到fib
的最后一个值小于num
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; fib[fib.length - 1] < num; i++) {
var next = fib[i - 1] + fib[i - 2];
fib.push(next);
}
return fib
.filter(x => !(x % 2))
.reduce((ac,a) => ac + a,0)
}
console.log(sumFibs(10));
答案 2 :(得分:0)
我想这就是你想要的:
function sumFibs(num) {
var fib = [1, 1];
var sum = 2;
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
if (next<=num && next % 2 != 0)
sum += next;
}
console.log("fib: " + fib);
console.log("sum: " + sum);
return sum;
}
console.log(sumFibs(10));
答案 3 :(得分:0)
如果您想保留大部分代码,则可以添加if
语句,一旦您的next
数超出num
,就可以中断循环:
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
if ( next > num ) { // not >= assuming you want to include your num
break;
}
fib.push(next);
}
console.log({fib});
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
答案 4 :(得分:0)
您的代码正在将前N个斐波那契数相加。您似乎正在寻找总和为N的第一个奇数斐波那契数:
function oddFibsThatAddTo(target)
{
let currentFib = 1;
let lastFib = 1;
let sum = 2;
const outs = [1,1];
while(sum < target)
{
let nextFib = currentFib + lastFib;
if(nextFib % 2 == 1)
{
sum += nextFib;
outs.push(nextFib);
}
lastFib = currentFib;
currentFib = nextFib;
}
if(sum > target)
{
throw 'can\'t find perfect sequence';
}
return outs;
}
console.log(oddFibsThatAddTo(10))
答案 5 :(得分:-1)
function sumFibs(num) {
var fib=[1,1];
for(var i=2; i<num; i++){
var next=fib[i-1]+fib[i-2];
var fibi=fib.push(next);
}
return fib.filter(function(a){
return(a%2!=0 && a<=num);
})
.reduce(function(a,z){
return a+z;
})
}
console.log(sumFibs(10));