Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

c# - Sum of even fibonacci numbers

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();                
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...