class Factorial_memoized { static memoList = [ ( 0G ) : 1 , ( 1G ) : 1 ] static iterative ( BigInteger n ) { if ( n < 0 ) { throw new FactorialIllegalArgumentException ( 'Parameter must be a non-negative integer.' ) } if ( memoList[n] ) { return memoList[n] } def total = 1G if ( n > 1 ) { for ( i in 2G..n ) { total *= i } } memoList[n] = total } static iterative ( Integer n ) { iterative ( new BigInteger ( n.toString ( ) ) ) } static iterative ( Long n ) { iterative ( new BigInteger ( n.toString ( ) ) ) } static recursive ( BigInteger n ) { if ( n < 0 ) { throw new FactorialIllegalArgumentException ( 'Parameter must be a non-negative integer.' ) } if ( memoList[n] ) { return memoList[n] } memoList[n] = n <= 1 ? 1 : n * recursive ( n - 1 ) } static recursive ( Integer n ) { recursive ( new BigInteger ( n.toString ( ) ) ) } static recursive ( Long n ) { recursive ( new BigInteger ( n.toString ( ) ) ) } static tailRecursive ( BigInteger n ) { if ( n < 0 ) { throw new FactorialIllegalArgumentException ( 'Parameter must be a non-negative integer.' ) } if ( memoList[n] ) { return memoList[n] } def iterate iterate = { i , result -> i < 2 ? 1 : iterate ( i - 1 , result * i ) } memoList[n] = iterate ( n , 1 ) } static tailRecursive ( Integer n ) { tailRecursive ( new BigInteger ( n.toString ( ) ) ) } static tailRecursive ( Long n ) { tailRecursive ( new BigInteger ( n.toString ( ) ) ) } }