甚至斐波纳契数的总和

这是项目欧拉问题。 如果你不想看到候选解决方案,请不要看这里。

大家好! 我正在开发一个应用程序,它将找到斐波那契序列的所有偶数项的总和。 该序列的最后一项是4,000,000。 我的代码有问题,但我找不到问题,因为它对我有意义。 你能帮我么?

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(); } } } 

将第一个for循环更改for

 for (i = 2; arr[i - 1] < 4000000; i++) 

使用此: http : //en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression

第三个身份这个身份对于Fj有不同的forms,这取决于j是奇数还是偶数。 第一个n – 1个斐波那契数Fj的总和,即j是奇数,是第(2n)个斐波纳契数。

前n个斐波那契数Fj的总和,即j是偶数,是第(2n + 1)个斐波那契数减1。

[16]

唯一的问题是当你将phi提高到(2n + 1)次幂时可能会损失精度。

在这个部分:

  long n= arr[i]; long s=0; for (i=2 ; n <= 4000000; i++) { arr[i] = arr[(i - 1)] + arr[(i - 2)]; } 

你只分配了一次; 永远不会更新,所以你的循环永远不会终止。

n 不限i ; n设置为arr[2]因为那时i是2。 所以, i将永远是循环的第一次迭代中的3。

要解决这个问题,一种方法是完全摆脱n并使你的循环条件

 for (i = 2; arr[i] <= 4000000; i++) 

试试这个(并将其用于您的大整数要求: http : //intx.codeplex.com/Wikipage ):

 using System; using System.Collections; using System.Linq; using System.Collections.Generic; using Oyster.Math; namespace Application { public class Test { public static void Main() { IntX even = 0; Console.WriteLine("Sum of even fibonacci {0}\n", Fibonacci(20).Where(x => x % 2 == 0).Sum()); Console.WriteLine("Sum of odd fibonacci {0}", Fibonacci(20).Where(x => x % 2 == 1).Sum()); Console.Write("\nFibonacci samples"); foreach (IntX i in Fibonacci(20)) Console.Write(" {0}", i); Console.ReadLine(); } public static IEnumerable Fibonacci(int range) { int i = 0; IntX very = 0; yield return very; ++i; IntX old = 1; yield return old; ++i; IntX fib = 0; while (i < range) { fib = very + old; yield return fib; ++i; very = old; old = fib; } } } public static class Helper { public static IntX Sum(this IEnumerable v) { int s = 0; foreach (int i in v) s += i; return s; } } } 

样本输出:

 Sum of even fibonacci 3382 Sum of odd fibonacci 7563 Fibonacci samples 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 

我承认我会以完全不同的方式做到这一点。 我可能会使用Lucas和Fibonacci数的配对序列,加上简单的公式

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

请注意,只有每三个Fibonacci数是偶数。 因此,由于F(3)= 2,L(3)= 4,我们得到

F(n + 3)= L(n)+ 2 * F(n)

L(n + 3)= 5 * F(n)+ 2 * L(n)

现在只是总结条款。

(编辑:有一个更简单的解决方案,这确实依赖于一些数学上的复杂性来推导,或者对该序列的Fibonacci序列和身份的一些了解,或者可能通过整数序列的百科全书进行搜索。可悲的是,更多因为这个提示似乎不适合PE问题,所以我将把这个解决方案留在本说明的边缘。因此,第一个k甚至Fibonacci数的总和是…)