Project Euler > Problem 2 > Even Fibonacci numbers (Java Solution)

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.


Solution:

4613732


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 2
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p002 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p002().run());
 }
 
 
 public String run() {
  int sum = 0;
  for (int i = 0; ; i++) {
   int fib = fibonacci(i);
   if (fib > 4000000)
    break;
   if (fib % 2 == 0)
    sum += fib;
  }
  return Integer.toString(sum);
 }
 
 
 private static int fibonacci(int x) {
  if (x < 0 || x > 46)
   throw new IllegalArgumentException();
  int a = 0;
  int b = 1;
  for (int i = 0; i < x; i++) {
   int c = a + b;
   a = b;
   b = c;
  }
  return a;
 }
 
}


2 comments :

  1. horribly inefficient. instead of calling a method hundreds of thousands of times, this code works and is way better for processing power.

    int sum = 2;
    int a = 1;
    int b = 2;
    //System.out.println(a + "\n" + b);

    while (a < 4000000) {
    int c = a;
    a = b;
    b = c + b;
    if (b % 2 == 0) {
    sum += b;
    }
    //System.out.println(b);
    }

    System.out.println(sum);

    ReplyDelete
  2. Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. seo expert

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact