Even Fibonacci numbers
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.
Snippet
public class Program
{public static void Main(string[] args){Console.WriteLine(Problem2.EvenFibonacciNumbers(4000000));}}class Problem2{internal static long EvenFibonacciNumbers(long limit){long curr = 1, next = 2, temp=0,res=2;while(true){temp = next;next += curr;if (next > limit) break;curr = temp;res = (next % 2 == 0) ? res + next : res;}return res;}}
Steps
First two numbers will be 1 and 2Take one temp variable to store next value
Next number will be sum of current and next
Assign value to current from temp
If number in the fibonacci series is divisible by 2, Add it to the result
No comments:
Post a Comment