階乘算法如下:
以下列出 0 至 20 的階乘:
0!=1,(0 的階乘是存在的)
1!=1,
2!=2,
3!=6,
4!=24,
5!=120,
6!=720,
7!=5040,
8!=40320
9!=362880
10!=3628800
11!=39916800
12!=479001600
13!=6227020800
14!=87178291200
15!=1307674368000
16!=20922789888000
17!=355687428096000
18!=6402373705728000
19!=121645100408832000
20!=2432902008176640000
而當 n≥5 時,n!的個位數字都是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 stub System.out.println("--------遞歸算法-------"); System.out.println(factorialRecursive(20)); System.out.println("--------循環算法-------"); System.out.println(factorialLoop(25)); System.out.println("--------BigDecimal算法-------"); System.out.println(factorial(new BigDecimal(100))); } /** * 遞歸實現階乘算法 * * @param n * @return */ public static long factorialRecursive(int n) { // 階乘對整數才有意義 if (n < 0) { return -1; } // 0!=1,(0 的階乘是存在的) if (n == 0) { return 1; } if (n < 2) return n * 1; return n * factorialRecursive(n - 1); } /** * 循環實現階乘算法 * @param n * @return */ public static long factorialLoop(int n) { // 階乘對整數才有意義 if (n < 0) { return -1; } // 0!=1,(0 的階乘是存在的) if (n == 0) { return 1; } // 初始值必須為1才有意義 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類型的1 BigDecimal bd2 = new BigDecimal(2);//BigDecimal類型的2</span><span> BigDecimal result = bd1;//結果集,初值取1 while(n.compareTo(bd1) > 0){//參數大於1,進入循環 result = result.multiply(n.multiply(n.subtract(bd1)));//實現result*(n*(n-1)) n = n.subtract(bd2);//n-2后繼續 } return result; } }