Project Euler 2: Even Fibonacci numbers


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.
This problem was originally featured on Project Euler.


Here we only need to learn how to compute Fibonacci numbers.

Program in Java:

 * Copyright (C) 2015 Pankaj @
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <>.

 * @author Pankaj
public class ProjectEuler2 {
    public static void main(String args[] ){
        long a,b,c, sum = 0L;
        a = 0;
        b = 0;
        c = 1;
        while(c<=4000000) {
                sum += c;
            a = b;
            b = c;
            c = a+b;

Happy coding ;)
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment