I am trying to solve Euler's Project #2 and I keep getting the answer as "Infinity" or "NaN" (Not a number) I tried changing the type of number to a int
(originally Double
), but that didn't fix anything just gave me the answer "-1833689714"
public class Pro {
static int g = 1;
static int n, f = 0;
public static void main(String args[]) {
for (int i = 0; i <= 4000000; i++) {
f = f + g;
g = f - g;
if (f % 2 == 0) {
n += f;
}
}
System.out.println("Answer: " + n);
}
}
The questions is:
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.