Java中的阶乘


/**
 * Description:阶乘 0! = 1,n! = (n-1)! * n;
 */
public class Factorial {

    public static int fac(int n){
        if(n == 0 | n == 1) return 1;
        if(n > 1) return fac(n-1)*n;
        else throw  new IllegalArgumentException("参数错误");
    }
    public static int fact(int n){
        int sum = 1;
        if (n == 0 | n == 1) return sum;
        if (n > 1){
            for (int i = 1; n >= i; i++){
                sum *= i;
            }
        } else throw new IllegalArgumentException("参数错误");
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(fac(6));
        System.out.println(fact(6));
    }
}
posted @ 2017-12-06 23:27  希望在田野上  阅读(363)  评论(0编辑  收藏  举报