6. แยกย่อย

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 6-20  เมท็อดหาจำนวนฟิโบนักชี (แบบวงวน)
public static int fib(int n) {
  if (n < 0) throw new IllegalArgumentException(n + " เป็นลบ");
  if (n == 0) return 0;
  if (n == 1) return 1;
  int fk2 = 0, fk1 = 1, fk = 1;
  for (int k=2; k<=n; k++) {
    fk = fk1 + fk2;
    fk2 = fk1;
    fk1 = fk;
  }
  return fk;
}
©2009 S.Prasitjutrakul