Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package problems;
- import java.math.BigInteger;
- /*
- ============================================================================
- Name : Problem1.java
- Author : Catarina Moreira
- Copyright : Catarina Moreira all rights reserved
- Description : Project EULER problem 2: Even Fibonacci numbers
- ============================================================================
- */
- public class Problem2
- {
- /*
- * 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.
- *
- */
- public int evenFibonacci(int n)
- {
- int result = 0;
- for( int i = 0; ; i++ )
- {
- int fib = getFibonacci( i );
- if( fib > n ) break;
- if( fib % 2 == 0 )
- result += fib;
- }
- return result;
- }
- public int getFibonacci( int n )
- {
- int a = 0, b = 1, c = 0;
- for(int i = 0; i < n; i++, a = b, b = c )
- c = a + b;
- return c;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement