Skip to content

Instantly share code, notes, and snippets.

@pkukielka
Created May 31, 2012 10:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pkukielka/2842475 to your computer and use it in GitHub Desktop.
Save pkukielka/2842475 to your computer and use it in GitHub Desktop.
Factorial in java with trampolines
import java.math.BigInteger;
class Trampoline<T>
{
public T get() { return null; }
public Trampoline<T> run() { return null; }
T execute() {
Trampoline<T> trampoline = this;
while (trampoline.get() == null) {
trampoline = trampoline.run();
}
return trampoline.get();
}
}
public class Factorial
{
public static Trampoline<BigInteger> factorial(final int n, final BigInteger sum)
{
if(n <= 1) {
return new Trampoline<BigInteger>() { public BigInteger get() { return sum; } };
}
else {
return new Trampoline<BigInteger>() {
public Trampoline<BigInteger> run() {
return factorial(n - 1, sum.multiply(BigInteger.valueOf(n)));
}
};
}
}
public static void main( String [ ] args )
{
System.out.println(factorial(100000, BigInteger.ONE).execute());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment