阶乘和阶乘求和

废话少说,直接上代码:

package com.hylink.common;

public class Factorial {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("阶乘...");
		System.out.println(factorial(0));
		System.out.println(factorial(1));
		System.out.println(factorial(2));
		System.out.println(factorial(3));
		System.out.println(factorial(4));
		System.out.println(factorial(5));
		System.out.println(factorial(6));
		System.out.println("------------------------------------------------");
		System.out.println("阶乘之和...");
		System.out.println(factorialAddSum(0));
		System.out.println(factorialAddSum(1));
		System.out.println(factorialAddSum(2));
		System.out.println(factorialAddSum(3));
		System.out.println(factorialAddSum(4));
		System.out.println(factorialAddSum(5));
		System.out.println(factorialAddSum(6));
	}

	//计算阶乘
	public static Integer factorial(int value){
		if(value > 1){
			return value * factorial(value - 1);
		}else if(value == 1){
			return 1;
		}
		return null;
	}
	
	//计算阶乘之和
	public static Integer factorialAddSum(int value){
		int sum = 0;
//		System.out.println(value);
//		for(int i = 1; i <= value; i++){
//			System.out.println("i的值是:"+i);
//			return sum += factorial(i);
//		}
		//上面是在for中return,故在第一次i=1时就返回了,故有误
		
		for(int i = 1; i <= value; i++){
//			System.out.println("i的值是:"+i);
			sum += factorial(i);
		}
		return sum;
	}
}


 

 

console print:

阶乘...
null
1
2
6
24
120
720
------------------------------------------------
阶乘之和...
0
1
3
9
33
153
873

你可能感兴趣的:(阶乘和阶乘求和)