Second problem from project Euler.
Feedback on better ways to do these are most welcome!
Question:
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.
Answer:
public class problem2 {
 public static void main(String[] args) {
  problem2 p = new problem2();
  int val = 0;
  int sum = 0;
  for (int i = 2; i < 102; i++) {
   val = p.fibonacci(i);
   if (val % 2 == 0) {
    if (val <= 4000000) {
     sum = sum + val;
    } else {
     break;
    }
   }
  }
  System.out.println(sum);
 }
 public int fibonacci(int n) {
  if (n == 0)
   return 0;
  else if (n == 1)
   return 1;
  else
   return fibonacci(n - 1) + fibonacci(n - 2);
 }
}
}
The good thing about project Euler is that each question relys on something learned in the previous. Also I would just like to point out that this is the first time in a long time that I have used recursion...dosn't seem to be used that much in the feild..
No comments:
Post a Comment