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.
I wrote a solution to this second problem from Project Euler, and would appreciate a review of it. Here's the code:
package Problems.Level_1;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Manish on 10/14/2015.
* find sum of even terms of Fibonacci series whose values do not exceed four million
*/
public class Problem_2 {
private List<Integer> generateFibonacci() {
List<Integer> numbers = new ArrayList<>();
int first = 1;
int last = 2;
numbers.add(first);
numbers.add(last);
int sum = 0;
//modify for loop to limit value = 4 mil?
//for(int i = 2; i < limit; i++)
while(sum <= 4000000){
sum = first + last;
numbers.add(sum);
first = last;
last = sum;
}
return numbers;
}
//method to generate int array from a List of integers
private int[] buildIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
}
//method to calculate sum of even items in array
private int calculateEvenSum(int[] numList){
int result = 0;
for(int i = 0; i < numList.length; i++) {
if(numList[i] % 2 == 0) {
result += numList[i];
}
}
return result;
}
public static void main(String[] args) {
Problem_2 p2 = new Problem_2();
//System.out.println("The first 10 numbers of the Fibonacci Series are: " + p2.generateFibonacci(10));
//System.out.println("Enter the limit.");
// int l = new Scanner(System.in).nextInt();
List<Integer> list = p2.generateFibonacci();
int[] numList = p2.buildIntArray(list);
int answer = p2.calculateEvenSum(numList);
System.out.println("The sum is: " + answer);
}
}
Right off the bat, I get that it might not be the best idea to generate an entire Fibnoacci sequence, the sum can probably be determined without that. Then there might be things like creating and storing a List
, creating and storing an array
from the List
, etc.
Does this solution cause too much of an unnecessary overhead?