日期:2014-05-20 浏览次数:20780 次
public class Test { public static void main(String[] args) { System.out.println("1 * 2 * 3 * 4 * 5 = " + factorial(5)); System.out.println("3 * 4 * 5 = " + factorial(3, 5)); } /** * 计算 num 的阶乘 * @param num * @return */ private static int factorial(int num) { return factorial(1, num); } /** * 计算 start * (start + 1) * (start + 2) * ... * end 的值 * @param start 阶乘的起始数 * @param end 阶乘的结束数 * @return */ private static int factorial(int start, int end) { if(start > end) { int t = start; start = end; end = t; } int result = start > 0 ? start : 1; while(end > start) { result *= end--; } return result; } }