MegaMind - 6 months ago 45
C# Question

# Create Fibonacci series using lambda operator

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

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();
``````
Source (Stackoverflow)