Project Euler Problems 1 to 100 - Problem 2: Even Fibonacci Numbers

Tell us what’s happening:

I do not understand the reason why I cannot pass the test. I tried it in Sublime and it worked there.

Your code so far

function fiboEvenSum(n) {
    let array = [1,2];
let sumOfNumbersInArray=2;
let arrayOfPrimeNumbers=[2];
let sumOfPrimeNumbers=2;
let sumOfNNumbers=0;
let arra = [];

for(let i=1;i<=n;i++){
    sumOfNumbersInArray=sumOfNumbersInArray+array[i-1];
    array.push(sumOfNumbersInArray);
    if(sumOfNumbersInArray%2===0){
           arrayOfPrimeNumbers.push(sumOfNumbersInArray)
           sumOfPrimeNumbers=sumOfPrimeNumbers+sumOfNumbersInArray;
    }

    for(let i=0;i<arrayOfPrimeNumbers.length;i++){
      
       if(arrayOfPrimeNumbers[i]<=n){
                        arra.push(arrayOfPrimeNumbers[i])
       }
    }
    
}
let sumOfArr=0;
let arrayWithoutDuplicates = [...new Set(arra)];
for(let i=0;i<arrayWithoutDuplicates.length;i++){
            sumOfArr=sumOfArr+arrayWithoutDuplicates[i];
}

return sumOfArr;

//console.log(arrayOfPrimeNumbers.length,sumOfArr, arrayWithoutDuplicates)


  
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36

Challenge Information:

Project Euler Problems 1 to 100 - Problem 2: Even Fibonacci Numbers

What error message do you have? I’m a bit dubious that this would pass any of the tests since I don’t think you are generating the Fibonacci numbers.

Edit: I think your variable names don’t agree with what is actually happening here. This problem has no prime numbers. Also, you’re making much more massive arrays than you need.

1 Like

Hi @santiagodeleondecar1

image

It looks like you have an infinite loop, so the tests are timing out.

Happy coding

1 Like

I did it over. Thanks for the suggestion.


function fiboEvenSum(n) {
    let thirdPosition=0;
    let arrayOfNumbers=[2];
    let firstPosition = 1;
    let secondPosition = 2;
    let sumOfNumbers=0;

    while(thirdPosition<=n){
    thirdPosition = firstPosition + secondPosition;
    firstPosition=secondPosition;
    secondPosition = thirdPosition;
    thirdPosition = firstPosition + secondPosition;
        
        if(thirdPosition%2==0){
              arrayOfNumbers.push(thirdPosition);
            }

        }

    for(    let i = 0;  i<arrayOfNumbers.length;    i++){

         sumOfNumbers   =   sumOfNumbers    +   arrayOfNumbers[i];

    }
   
   return sumOfNumbers;
}

That looks like it should run much faster!

You can make a tiny, tiny tweak to make it a bit faster

Note that the pattern is
1, 1, 2, 3, 5, 8, 13, 21, 34,… What’s the pattern with the even numbers?

1 Like

Each even number is every third position, therefore the sum of two odd numbers.

Right, so if you rearrange your logic a tiny bit, you never need to check % 2 === 0