Hai all
i try to solve the this problem:
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.
and here is my code:
public class Fibonacci { public static void main(String[] args) { int firstNum = 1; int seqNum = 0; int secNum = 1; long length = 1000 * 4000; int sumEvenNum = 0; System.out.println("length " + length); while (seqNum < length) { seqNum += firstNum; if (seqNum % 2 == 0) { //System.out.println("seqNum: " + seqNum); //System.out.println("sumEvenNum: " + sumEvenNum); sumEvenNum += seqNum; //System.out.println("even number: " + sumEvenNum); } firstNum = secNum; secNum = seqNum; } System.out.println("sumEvenNum: " + sumEvenNum); } }
But the result is: 4613732, exceed four million, while the question require the value not exceed four million. can you help me to solve this problem??.