Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of even fibonacci numbers

Tags:

c#

fibonacci

This is a Project Euler problem. If you don't want to see candidate solutions don't look here.

Hello you all! I'm developing an application that will find the sum of all even terms of the fibonacci sequence. The last term of this sequence is 4,000,000 . There is something wrong in my code but I cannot find the problem since it makes sense to me. Can you please help me?

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           long[] arr = new long [1000000] ;
           long i= 2;
           arr[i-2]=1;
           arr[i-1]=2;
           long n= arr[i];

           long s=0;
            for (i=2 ; n <= 4000000; i++)
            {                    
                arr[i] = arr[(i - 1)] + arr[(i - 2)];
            }
            for (long f = 0; f <= arr.Length - 1; f++)
            {
                if (arr[f] % 2 == 0)
                    s += arr[f];
            }
            Console.Write(s);
            Console.Read();                
        }
    }
}
like image 312
user300484 Avatar asked Feb 28 '23 06:02

user300484


2 Answers

Use this: http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression

Third identity This identity has slightly different forms for Fj, depending on whether j is odd or even. The sum of the first n − 1 Fibonacci numbers, Fj, such that j is odd, is the (2n)th Fibonacci number.

The sum of the first n Fibonacci numbers, Fj, such that j is even, is the (2n + 1)th Fibonacci number minus 1.

[16]

The only problem is potential loss of precision when you raise phi to the (2n + 1)th power.

like image 121
Hamish Grubijan Avatar answered Mar 06 '23 20:03

Hamish Grubijan


In this section:

       long n= arr[i];

       long s=0;
        for (i=2 ; n <= 4000000; i++)
        {

            arr[i] = arr[(i - 1)] + arr[(i - 2)];
        }

You've only assigned n once; n never updates, so your loop will never terminate.

n is not bound to i; n is set to arr[2] because i was 2 at that point. So, i will be 3 from the first iteration of the loop forever.

To fix this, one approach would be to get rid of n altogether and make your loop condition

for (i = 2; arr[i] <= 4000000; i++)
like image 20
Mark Rushakoff Avatar answered Mar 06 '23 21:03

Mark Rushakoff