Created
May 5, 2017 16:10
-
-
Save farhadfaghihi/11d0b6fcaed8a14e41f12a85c328c62a to your computer and use it in GitHub Desktop.
Head vs. Tail Recursive
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 ir.jibmib; | |
import java.math.BigInteger; | |
public class Main { | |
public static void main(String[] args) { | |
try{ | |
BigInteger result = tailRecFactorial(1000,BigInteger.valueOf(1)) ; | |
System.out.println(result); | |
} | |
catch (Throwable exc) { | |
System.out.println(exc.getMessage()); | |
} | |
} | |
private static BigInteger headRecFactorial(int n) { | |
if(n == 0) | |
return BigInteger.valueOf(1l); | |
return BigInteger.valueOf(n).multiply(headRecFactorial(n-1)); | |
} | |
private static BigInteger tailRecFactorial(int n, BigInteger accumulator) { | |
if(n <= 1) | |
return accumulator ; | |
return tailRecFactorial(n-1,BigInteger.valueOf(n).multiply(accumulator)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment