Created
August 13, 2013 07:58
-
-
Save emre/6218851 to your computer and use it in GitHub Desktop.
Even Fibonacci numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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. | |
| */ | |
| public class EvenFibonacci { | |
| public int fibonacci() { | |
| int sum = 0; | |
| int a = 0; | |
| int b = 1; | |
| int n = 50; | |
| for (int i=0; i < n; i++) { | |
| int c = a + b; | |
| a = b; | |
| b = c; | |
| if (b % 2 == 0) { | |
| sum += b; | |
| } | |
| if(b > 4000000) { | |
| break; | |
| } | |
| } | |
| return sum; | |
| } | |
| public static void main(String[] arguments) { | |
| System.out.println(new EvenFibonacci().fibonacci()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment