Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fibonacci;
- public class FibonacciTask {
- public static void main(String[] args) {
- System.out.println(calculateEvenFibonacciNumbersBefore4000000Sum());
- }
- // Finds the sum of the even-valued Fibonacci sequence terms, whose values do not exceed four million
- // I didn't use recursive fibonacci numbers algorithm, because i think this one is more optimal
- static int calculateEvenFibonacciNumbersBefore4000000Sum(){
- int prev = 0, next = 1, fibonacciNumber = 0, sum = 0;
- while (fibonacciNumber <= 4000000){
- if(isEven(fibonacciNumber))
- sum += fibonacciNumber;
- fibonacciNumber = prev + next;
- prev = next;
- next = fibonacciNumber;
- }
- return sum;
- }
- // Parity check
- static boolean isEven(int number){
- return number % 2 == 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement