public class Fibonacci { /* USING ITERATION */ /* returns the nth term in the Fibonacci sequence */ public static int fibonacci(int n) { int i = 0, j = 1, temp; for (int term = 1; term < n; term++) { temp = i; i = j; j += temp; } return j; } /* USING RECURSION */ /* params: i and j are intial two Fibonacci terms; n is the nth term from j return: the nth term of the Fibonacci sequence (starting from i = 1st term) */ public static int fibonacci(int i, int j, int n) { if (n > 0) return fibonacci(j, i+j, n-1); // next term; reduce the number of terms left else // completed all terms return i; } public static void main(String[] args) { System.out.println(fibonacci(1)); // 1 System.out.println(fibonacci(2)); // 1 System.out.println(fibonacci(6)); // 8 System.out.println(fibonacci(12)); // 144 System.out.println(fibonacci(0, 1, 1)); // 1 System.out.println(fibonacci(0, 1, 2)); // 1 System.out.println(fibonacci(0, 1, 6)); // 8 System.out.println(fibonacci(0, 1, 12)); // 144 } }DOWNLOAD
Created: May 15, 2014
Last Updated: September 21, 2014
Completed in full by: Michael Yaworski