Potential infinite loop on js intermediate algorithms

i m working on sumOddFibonacci numbers i tried my solution on vs code it s working for all the nums in the tests but when i try to test on the fcc plateform an error occurs while testing sumFibs(4000000)
here is my code well i c the point why it s a potential infinite loop but idk why it s not passing the test here s my code

const isPerfectSquare=(y)=>
{
  let s =parseInt(Math.sqrt(y))
  return s*s == y
}
const isFibonacci=(x)=>
{
  if (x < 0 )
{
  return false;
}
if(((isPerfectSquare(5*x*x+4)) || (isPerfectSquare(5*x*x-4))))
{
  return true;
}
else return false
}
const isOdd=(y)=>
{
if (y%2 !==0)
return true;
else return false
}
function sumFibs(num) {
let sum=1;
for(let i=0;i<=num;i++)
{
  if ((isOdd(i)) && (isFibonacci(i)))
  {
    sum=sum+i
  }
}
return sum
}

console.log(sumFibs(75025));

I haven’t done this section in a while but I recall that there is a requirement to be efficient. If your code takes too long it may be timing out the test.

ps. Post a link to the challenge so people can try your code…

I edited your post, one line of the code wasn’t visible
and here it is prettified so it is easier to read

const isPerfectSquare = (y) => {
  let s = parseInt(Math.sqrt(y));
  return s * s == y;
};
const isFibonacci = (x) => {
  if (x < 0) {
    return false;
  }
  if (isPerfectSquare(5 * x * x + 4) || isPerfectSquare(5 * x * x - 4)) {
    return true;
  } else return false;
};
const isOdd = (y) => {
  if (y % 2 !== 0) return true;
  else return false;
};
function sumFibs(num) {
  let sum = 1;
  for (let i = 0; i <= num; i++) {
    if (isOdd(i) && isFibonacci(i)) {
      sum = sum + i;
    }
  }
  return sum;
}

console.log(sumFibs(75025));

Yeah, this is an inefficient approach. You can directly create all fibs below the threshold.

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers here it s however there s no efficiency test it seems there s a limit of iterations maybe,actually 4000000 is a big number of iterations it s not passing the test just for this number

There is an ‘efficiency test’. The test with the big value is to ensure that you don’t use too inefficient of an approach. Your code is failing because it is too inefficient.

The infinite loop warning means that your code is taking too long.

1 Like

i see the point thanks for the help

1 Like