Created
February 19, 2014 23:55
-
-
Save paul-jean/9104120 to your computer and use it in GitHub Desktop.
Implement the factorial function using regular recursion, then again using tail recursion.
This file contains hidden or 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 Factorial { | |
| public static long fact(long n) { | |
| if (n == 0) return 1; | |
| return n * fact(n - 1); | |
| } | |
| public static long factTail(long n, long acc) { | |
| if (n == 1) return acc; | |
| return factTail(n - 1, n * acc); | |
| } | |
| public static void main(String[] args) { | |
| System.out.println("fact(5) ="); | |
| System.out.println(fact(5)); | |
| System.out.println("factTail(5, 1) ="); | |
| System.out.println(factTail(5, 1)); | |
| // Largest n for which n! < 2^63-1 is n = 20 | |
| System.out.println("fact(20) ="); | |
| System.out.println(fact(20)); | |
| System.out.println("factTail(20, 1) ="); | |
| System.out.println(factTail(20, 1)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment