计算阶乘
1 package com.jdk7.chapter1; 2 3 public class Factorial { 4 /** 5 * 计算n!的值,利用公式n×(n-1)×(n-2)×(n-3)×...×3×2×1 6 * 注:当n大于17时n!会超出long的取值范围 7 */ 8 public long getFactorial(int n){ 9 if(n<0 || n>17){ 10 System.out.println("n的取值区间为[0,17]"); 11 return -1; 12 }else if(n==0){ 13 return 1; 14 }else{ 15 long result = 1; 16 for(;n>0;n--){ 17 result *=n; 18 } 19 return result; 20 } 21 22 } 23 24 public static void main(String[] args) { 25 Factorial f = new Factorial(); 26 System.out.println(f.getFactorial(4)); 27 System.out.println(f.getFactorial(17)); 28 System.out.println(f.getFactorial(18)); 29 System.out.println(f.getFactorial(0)); 30 System.out.println(f.getFactorial(-2)); 31 } 32 33 } 34 35 执行结果: 36 24 37 355687428096000 38 n的取值区间为[0,17] 39 -1 40 1 41 n的取值区间为[0,17] 42 -1