Created
May 14, 2012 14:22
-
-
Save ilovejs/2694268 to your computer and use it in GitHub Desktop.
Tail Recursion Fibonacci Sequence
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
public class TailRecursion { | |
//implement fibonacci function | |
public static void main(String[] args) { | |
TailRecursion t = new TailRecursion(); | |
int normal = t.nFibo(9); | |
System.out.println(normal); | |
int tail = t.tailFibo(9); | |
System.out.println(tail); | |
} | |
//normal calculation | |
public int nFibo(final int n){ | |
if(n <= 2) | |
return 1; | |
return nFibo(n-1) + nFibo(n-2); | |
} | |
//tail recursion version | |
public int tailFibo(int n){ | |
return tailAux(n,3,1,1); | |
} | |
public int tailAux(int n, int i, int seclast, int last){ | |
if(i >= n) | |
return last+seclast; | |
return tailAux(n, i+1, last, seclast + last); | |
} | |
//1,1,2,3 | |
//2,2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment