Euler 2 – C# (Brute force)

Question:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Logic:
To represent the Fibonacci sequence in programming we assign the first and second numbers (1 and 2) and a sum representing the next number in the sequence
int fib1 = 1;
int fib2 = 2;
int fib3 = 0; //this will be fib1 + fib2
int total = 0;

Now we must set a limit of under 4 million in the sequence and write the sequence logic in a while loop
while(fib3 < 4000000) { //fib3 returns the highest value in the sequence
if (fib2 % 2 == 0) { //if condition searches for even numbers in the sequence
total += fib2; //total is added by fib2 every iteration that passes the if statement
}
fib3 = fib1 + fib2;
fib1 = fib2;
fib2 = fib3;
}
Console.WriteLine(total); //Answer is 4613732

Leave a Reply

Your email address will not be published. Required fields are marked *