import java.math.BigDecimal;
import java.util.stream.Stream;
public class TailSelf {
public static void main(String[] args) {
System.out.println(factorial(1000000));
}
public static String factorial(final long number) {
return tailRecursion(number, new BigDecimal(1)).invoke().toString();
}
private static TailLoop<BigDecimal> tailRecursion(long n, BigDecimal total) {
if (n == 1) {
return new TailLoop<BigDecimal>() {
@Override
public TailLoop<BigDecimal> functionalMethod() {
return null;
}
public BigDecimal result() {
return total;
}
};
}
return () -> tailRecursion(n - 1, total.multiply(new BigDecimal(n)));
}
@FunctionalInterface
interface TailLoop<T> {
TailLoop<T> functionalMethod();
default T result() {
return null;
}
default T invoke() {
// 惰性求值
return Stream.iterate(this, TailLoop::functionalMethod).filter((loop) -> loop.result() != null).findFirst()
.get().result();
}
}
}
知识点
- 尾递归
- 惰性求值
- java8 : lambda Stream
- 柯里化