Created
August 24, 2013 23:12
-
-
Save kmdarshan/6330926 to your computer and use it in GitHub Desktop.
Fibonacci sequence [ iterative/recursive/cached] with timers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package programs; | |
public class Fibonacci { | |
public static int fibrecursive(int n) { | |
if(n<=1){ | |
return n; | |
} | |
return fibrecursive(n-1)+fibrecursive(n-2); | |
} | |
public static void fibhelper(int n){ | |
for(int i = 0;i < n;++ i) | |
{ | |
System.out.print(fibrecursive(i)+" "); | |
// fibrecursive(i); | |
} | |
} | |
/** | |
* fibonacci sequence with caching implemented | |
*/ | |
static int arr[] = new int[100]; | |
public static void fibWithCaching(int n) { | |
int j=0; | |
arr[0]=0; | |
arr[1]=1; | |
for(j=0; j<n; j++) | |
{ | |
System.out.print(arr[j] + " "); | |
} | |
try{ | |
arr[n] = arr[j-1] + arr[j-2]; | |
System.out.println(); | |
}catch(IndexOutOfBoundsException e){ | |
// System.out.println("exception"); | |
} | |
} | |
/*non recursive fibonacci function*/ | |
public static void fibIterative(int n) | |
{ | |
int prev = -1; | |
int next = 1; | |
int sum; | |
int i; | |
for(i = 0;i < n;++ i) | |
{ | |
sum = next + prev; | |
prev = next; | |
next = sum; | |
arr[i] = next; | |
System.out.print(next + " "); | |
if(i == n-1){ | |
System.out.println(); | |
} | |
} | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
int limit = 20; | |
long starttime0 = System.nanoTime(); | |
for(int i = 0;i <= limit;++ i) | |
{ | |
fibhelper(i); | |
System.out.println(); | |
} | |
long estimatedTime0 = System.nanoTime() - starttime0; | |
System.out.println(estimatedTime0); | |
long starttime1 = System.nanoTime(); | |
for(int i = 0;i <= limit;++ i) | |
{ | |
fibIterative(i); | |
} | |
long estimatedTime1 = System.nanoTime() - starttime1; | |
System.out.println(estimatedTime1); | |
long starttime2 = System.nanoTime(); | |
for(int i = 0;i <= limit;++ i) | |
{ | |
fibWithCaching(i); | |
} | |
long estimatedTime2 = System.nanoTime() - starttime2; | |
System.out.println(estimatedTime2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment