# Project Euler 2 - Even Fibonacci Numbers - Solved with C#

The second Project Euler problem - Even Fibonacci Numbers - is stated as follows - By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

``````using System;
using System.Linq;

public class Program
{
// Returns true if if N is a perfect square,
// i.e. N can be expressed as the product
// of two equal integers.
static bool isPerfectSquare(long x)
{
long s = (long)Math.Sqrt(x);
return (s * s == x);
}

// Returns true if N is in the Fibonacci sequence.
static bool isFibonacci(long n)
{
// M is Fibonacci if and only if one or both of
// 5*n*n + 4 or 5*n*n - 4 is a perfect square.
// https://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers
return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4);
}

// Returns true if N is even.
static bool isEven(int n)
{
return n % 2 == 0;
}

public static void Main()
{
// Generate a range from 1 to 4 million.
long sum = Enumerable.Range(1, 4000000)
// Take only fibonacci numbers...
.Where(n => isFibonacci((long)n))
// ...that are even.
.Where(isEven)
.Sum();

Console.WriteLine(sum);
}
}``````