12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- import java.util.ArrayList;
- public class EvenFibonacciNumbers {
- public static ArrayList<Integer> getFibonacciNumbersInRange() {
- int[] nums = {1, 2};
- int fibNum = 0;
- ArrayList<Integer> fibNums = new ArrayList<Integer>();
- for (int i = 1; i < 4000000; i++) {
- if (i == 1 || i == 2)
- fibNum = i;
- else {
-
- fibNum = nums[0] + nums[1];
-
- nums[0] = nums[1];
- nums[1] = fibNum;
- }
-
- if (fibNum <= 4000000)
- fibNums.add(fibNum);
- else
- break;
- }
- return fibNums;
- }
- private static int getSumOfEvenFibonacciNumbers(ArrayList<Integer> fibNums) {
- int sum = 0;
- for (int num : fibNums) {
- if (num % 2 == 0)
- sum += num;
- }
- return sum;
- }
- public static void main(String[] args) {
-
- ArrayList<Integer> fibNums = getFibonacciNumbersInRange();
- int evenFibSum = getSumOfEvenFibonacciNumbers(fibNums);
- System.out.println(evenFibSum);
- }
- }
|