Fibonacci Sequence

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.

In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence: 0,1,1,2,3,5,8,13,21,34,55,89,144 (sequence A000045 in OEIS).

By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the
sum of the previous two.

public class Problem2 {
    public void Fibonacci() {
        long limit = 4000000l;
        long sum = 0, a=1, b=1;
        while (b<limit) {
            if (b%2==0)
                sum+=b;
            long h = a+b;
            a=b;
            b=h;
        }
        System.out.println(sum);
    }

    public void FibonacciPE1() {
        /*
        Now let us see if we can get rid of the testing for even values.
        Here is the beginning of the Fibonacci sequence with even numbers in red:
        1 1 2 3 5 8 13 21 34 55 89 144 ...
        a b c a b c a  b  c  a  b  c
        It is easy to prove that every third Fibonacci number is even.
        It is not so difficult to change the program somewhat so that only every third number is added:
         */
        long limit = 4000000l;
        long sum = 0, a=1, b=1,c=a+b;
        while (c<limit) {
            sum+=c;
            a = b+c;
            b = c+a;
            c= a+b;
        }
        System.out.println(sum);
    }

    public static void main(String[] args) {
        Problem2 p = new Problem2();
        p.FibonacciPE();
        p.FibonacciPE1();
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: