/** * Factorial calculation with straightforward way. * @param num * @return */ public static double mathFactorial(int num) { //----- to prevent abnormal result Ts.assertTrue(num >= 0 && num <= 143, "factorial: the range is from 0 to 143"); double result = 1; for (int i = 1; i <= num; i++) { result *= i; } return result; } /** * Factorial calculation with Stirling approximation. * @param num * @return */ public static double mathFactorialStirling(int num) { if (num == 0) { return 1.0; } Ts.assertTrue(num >= 0 && num <= 142, "factorial: the range is from 0 to 142"); return Math.sqrt(2 * Math.PI * num) * Math.pow(num, num) * Math.pow(Math.E, -num); } public static void assertTrue(boolean isTrue, String message) { if (!isTrue) { System.out.println("---> Assert fail : " + message); new Exception().printStackTrace(); System.exit(-1); } }