Skip to content

Instantly share code, notes, and snippets.

@farhadfaghihi
Created May 5, 2017 16:10
Show Gist options
  • Save farhadfaghihi/11d0b6fcaed8a14e41f12a85c328c62a to your computer and use it in GitHub Desktop.
Save farhadfaghihi/11d0b6fcaed8a14e41f12a85c328c62a to your computer and use it in GitHub Desktop.
Head vs. Tail Recursive
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