Created
May 31, 2012 10:25
-
-
Save pkukielka/2842475 to your computer and use it in GitHub Desktop.
Factorial in java with trampolines
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
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