EvenFibonacciNumbers.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import java.util.ArrayList;
  2. public class EvenFibonacciNumbers {
  3. public static ArrayList<Integer> getFibonacciNumbersInRange() {
  4. int[] nums = {1, 2};
  5. int fibNum = 0;
  6. ArrayList<Integer> fibNums = new ArrayList<Integer>();
  7. for (int i = 1; i < 4000000; i++) {
  8. if (i == 1 || i == 2)
  9. fibNum = i;
  10. else {
  11. // To get the next number in the Fibonacci sequence
  12. fibNum = nums[0] + nums[1];
  13. // To set each index of the array to the correct Fibonacci number
  14. nums[0] = nums[1];
  15. nums[1] = fibNum;
  16. }
  17. /* To add each Fibonacci number to the ArrayList, if less than equal
  18. to 4 million */
  19. if (fibNum <= 4000000)
  20. fibNums.add(fibNum);
  21. else
  22. break;
  23. }
  24. return fibNums;
  25. }
  26. private static int getSumOfEvenFibonacciNumbers(ArrayList<Integer> fibNums) {
  27. int sum = 0;
  28. for (int num : fibNums) {
  29. if (num % 2 == 0)
  30. sum += num;
  31. }
  32. return sum;
  33. }
  34. public static void main(String[] args) {
  35. /* Each new term in the Fibonacci sequence is generated by adding the
  36. previous two terms. By starting with 1 and 2, the first 10 terms will be:
  37. 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  38. By considering the terms in the Fibonacci sequence whose values do not
  39. exceed four million, find the sum of the even-valued terms.
  40. */
  41. ArrayList<Integer> fibNums = getFibonacciNumbersInRange();
  42. int evenFibSum = getSumOfEvenFibonacciNumbers(fibNums);
  43. System.out.println(evenFibSum);
  44. }
  45. }