The factorial algorithm is as follows: 0 to 20 of the factorial: 0! =1, (the factorial of 0 is present) 1! =1,2! =2,3! =6,4! =24,5! =120,6! =720,7! =5040,8! =403209! =36288010! =362880011! =3991680012! =47900160013! =622702080014! =8717829120015! =130767436800016! =2092278988800017! =35568742809600018! =640237370572800019! =12164510040883200020! =2432902008176640000 and when N≥5, n! The single digit is 0.
Package Com.leo.kang.interview;import Java.math.bigdecimal;public class Factorial {/** * @param args */public static void Main (string[] args) {//TODO auto-generated method StubSystem.out.println ("--------recursive algorithm-------"); System.out.println (Factorialrecursive (20)); System.out.println ("--------Loop algorithm-------"); System.out.println (Factorialloop (25)); System.out.println ("--------BigDecimal algorithm-------"); System.out.println (Factorial (new BigDecimal (100))); /** * Recursive implementation of factorial algorithm * * @param n * @return */public static long factorialrecursive (int n) {//factorial is meaningful to integers if (n < 0) {return- 1;} 0! =1, (the factorial of 0 is present) if (n = = 0) {return 1;} if (n < 2) return n * 1;return n * factorialrecursive (n-1);} /** * Loop implementation factorial algorithm * @param n * @return */public static long factorialloop (int n) {//factorial to integer only meaningful if (N < 0) {return-1;} 0! =1, (the factorial of 0 is present) if (n = = 0) {return 1;} The initial value must be 1 to make sense long result = 1;for (int i = n; i > 0; i--) {result *= i;} return result;} public static BigDecimal factorial (BigDecimal N) {BigDecimal BD1 =New BigDecimal (1);//bigdecimal type of 1 BigDecimal bd2 = new BigDecimal (2);//bigdecimal type 2</span><span> BigDecimal result = bd1;//results set, initial value takes 1 while (N.compareto (BD1) > 0) {//parameter is greater than 1, enter loop result = ResU Lt.multiply (N.multiply (N.subtract (BD1)));//Implementation result* (n (n-1)) n = n.subtract (BD2);//n-2 and Continue} return result; } }
Java implementation factorial algorithm