Advertisement
Guest User

Untitled

a guest
May 29th, 2015
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. package fibonacci;
  2.  
  3. public class FibonacciTask {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. System.out.println(calculateEvenFibonacciNumbersBefore4000000Sum());
  8.  
  9. }
  10. // Finds the sum of the even-valued Fibonacci sequence terms, whose values do not exceed four million
  11. // I didn't use recursive fibonacci numbers algorithm, because i think this one is more optimal
  12. static int calculateEvenFibonacciNumbersBefore4000000Sum(){
  13.  
  14. int prev = 0, next = 1, fibonacciNumber = 0, sum = 0;
  15.  
  16. while (fibonacciNumber <= 4000000){
  17.  
  18. if(isEven(fibonacciNumber))
  19.  
  20. sum += fibonacciNumber;
  21.  
  22. fibonacciNumber = prev + next;
  23.  
  24. prev = next;
  25.  
  26. next = fibonacciNumber;
  27.  
  28. }
  29. return sum;
  30. }
  31.  
  32. // Parity check
  33. static boolean isEven(int number){
  34.  
  35. return number % 2 == 0;
  36.  
  37. }
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement