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();
}
}
}
try this (and use this for your big integer requirements: http://intx.codeplex.com/Wikipage ) :
Sample Output:
I'll admit that I would do this entirely differently. I would probably use the paired sequence of Lucas and Fibonacci numbers, plus the simple formulas
F(n+a) = (F(a)*L(n) + L(a)*F(n))/2
L(n+a) = (5*F(a)*F(n) + L(a)*L(n))/2
Note that only every third Fibonacci number is even. So since F(3) = 2, and L(3) = 4, we get
F(n+3) = L(n) + 2*F(n)
L(n+3) = 5*F(n) + 2*L(n)
Now just sum the terms.
(edit: There is an even easier solution to this, that does rely on some mathematical sophistication to derive, or some knowledge of the Fibonacci sequence and identities for that sequence, or perhaps a search through the encyclopedia of integer sequences. Sadly, any more than this hint seems inappropriate for a PE problem, so I'll leave that solution in the margins of this note. Thus, the sum of the first k even Fibonacci numbers is...)
Change the first
for
loop to this: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.
In this section:
You've only assigned
n
once;n
never updates, so your loop will never terminate.n
is not bound toi
;n
is set toarr[2]
becausei
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