Problem 2: Even Fibonacci numbers

*Difficulty: Easy

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.

How to solve:

First, we create a variable type int (or long) to store the total value, this variable is initialized by 2 (2 is the smallest even-valued term). And two numbers, for example, name n1 and n2 , initialized with 1 and 2, respectively. Moreover, we need a variable represent the Fibonacci value, you can name it whatever you want, I call it fibo (for short). We loop until fibo is still <= 4 millions , add n1 and n2 , assign that value to fibo, then we assign n2 to n1, and fibo to n2.
fibo = n1 + n2;

n1 = n2;

n2 = fibo;

And then see if fibo is an even number , if it is, add fibo to sum

sum += fibo;

Implementation (Java):

public class Prob2 {

        private static final intTHRESHOLD = 4000000;

        public static void main(String[] args) {

               int n1 = 1;

               int n2 = 2;

               int fibo = 0;

               //2 is the smallest even-valued term

              int sum = 2;

              long cur = System.currentTimeMillis();

             do {

                     fibo= n1+n2;

                     n1 = n2;

                     n2= fibo;

                     if(fibo % 2 == 0) {

                                sum+= fibo;

                     System.out.println(fibo);

                    }

           }while(fibo <= THRESHOLD);

           System.out.println(sum);

           System.out.println("Took " + (System.currentTimeMillis()-cur) + "ms");

     }

}

Solution took 0ms

Advertisements