Finding Fibonacci sequence in C#. [Project Euler Exercise]

后端 未结 9 2292
后悔当初
后悔当初 2021-02-06 19:22

I\'m having some trouble with this problem in Project Euler.

Here\'s what the question asks:

Each new term in the Fibonacci sequence is generated by adding t

9条回答
  •  广开言路
    2021-02-06 19:39

    One of the fun feature in C# is the "yield" keyword, which is very useful for this kind of thing:

    IEnumerable Fibonacci()
    {
       int n1 = 0;
       int n2 = 1;
    
       yield return 1;
       while (true)
       {
          int n = n1 + n2;
          n1 = n2;
          n2 = n;
          yield return n;
       }
    }
    
    long result=0;
    
    foreach (int i in Fibonacci().TakeWhile(i => i<4000000).Where(i => i % 2 == 0))
    {
        result+=i;
    }
    Console.WriteLine(result);
    

    The "traditional" recursive Fibonacci implementation is problematic here because it throws away all the work done along the way to the last requested term. You would have to call such a function over and over in a loop, which would duplicate a lot of work, or you could start with that implementation and add an argument to the recursive function to build up the desired sum result as the final fibonacci term is calculated. I like this much better, because it's still a general purpose fibonacci sequence at the core, rather than one you had to re-write or specialize.

    Another approach is to use events (delegates) in a traditional implementation to call a separate method as each term is completed, but as I still like the iterator method better I'll leave the delegate option as an exercise for the reader.

提交回复
热议问题