Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Fibonacci series using lambda operator

Tags:

c#

lambda

I am trying to solve a question in Project Euler, which is creating a fibonacci series until 4 million, and add the even numbers that come in the series, this is obviously very easy task and I answer it in 2 mins,

int result=2;
int first=1;
int second=2;
int i=2;

while (i < 4000000)
{
    i = first + second;

    if (i % 2 == 0)
    {
       result += i;
    }

    first = second;
    second = i;
 }

 Console.WriteLine(result);

but I want to do it using a lambda expression

My effort is going like

DelType del = (oldVal, newVal) =>((oldVal==0?1:newVal  + newVal==1?2:oldVal+newVal) % 2 == 0) ? oldVal + newVal : 0;

int a=del(0, 1);

Kindly suggest how to get this done

like image 543
Manvinder Avatar asked Dec 25 '11 07:12

Manvinder


2 Answers

My first answer was having misread the question completely, but now I've reread it (thanks MagnatLU!) I'd suggest that this isn't a good fit for lambda expressions. However, it's a brilliant fit for a combination of iterator blocks and LINQ:

// Using long just to avoid having to change if we want a higher limit :)
public static IEnumerable<long> Fibonacci()
{
    long current = 0;
    long next = 1;
    while (true)
    {
        yield return current;
        long temp = next;
        next = current + next;
        current = temp;
    }
}

...

long evenSum = Fibonacci().TakeWhile(x => x < 4000000L)
                          .Where(x => x % 2L == 0L)
                          .Sum();
like image 65
Jon Skeet Avatar answered Oct 22 '22 03:10

Jon Skeet


Use this recursive function

Func<int, int> fib = null;
fib = (x) => x > 1 ? fib(x-1) + fib(x-2) : x;

Example Usage:

Console.WriteLine(fib(10));
like image 43
Shraddha Avatar answered Oct 22 '22 05:10

Shraddha