Factorial by Different Styles in Java

Here is a collection of methods of calculating factorial by different programming styles.

class Factorial {

    // Iteration
    static long iterativeFactorial(int n) {
        long r = 1;
        for (int i=1; i<=n; i++) r*=i;
        return r;
    }

    // Recursion
    static long recursiveFactorial(int n) {
        return n == 0 ? 1 : n * recursiveFactorial(n-1);
    }

    // Tail-recursion
    static long tailRecurFactorial(int n) {
        return tailRecurHelper(1L, n);
    }
    static long tailRecurHelper(long acc, int n) {
        return n == 0 ? acc : tailRecurHelper(acc*n, n-1);
    }

    // Lambda and Recursion
    static Function<Integer, Long> lambdaRecurFactorial = x -> x==0 
        ? 1L 
        : x * Factorial.lambdaRecurFactorial.apply(x-1);

    // Stream
    static long streamFactorial (int n) {
        return LongStream.rangeClosed(1, n)
                         .reduce(1, (a, b) -> a*b);
    }
    
    // Lambda and Stream
    static Function<Integer, Long> lambdaStreamFactorial = n -> 
        LongStream.rangeClosed(1, n)
                  .reduce(1, (a, b) -> a*b);                       

    // Lambda and Parallel Stream
    static Function<Integer, Long> lambdaParallelStreamFactorial = n -> 
        LongStream.rangeClosed(1, n)
                  .parallel()
                  .reduce(1, (a, b) -> a*b);                       

}

The minimalist methods above are for demonstrating the expressiveness of the Java language.  For research or practical use, further consideration is necessary.  long is 64-bit, thus has the maximum value of 9,223,372,036,854,775,808. The proper parameter n is limited to the range of [0, 20] where n is an integer.  When n is 20, the return value is 2,432,902,008,176,640,000.  Overflow will occur when n > 20.

For returning very large values, consider using BigInteger; and for dealing with parameter passing beyond an acceptable limit, throwing Exception.

Comments

Popular posts from this blog

Finding Median by Stream

Reduction by Java Stream