编写算法,计算下面表达式的值:
1 + (1+2 + 1 * 2)+ (1+2+3 + 1 * 2 * 3) +…+ (1+2+…+n + 1 * 2 *…*n);
public class AutoTest {
public static Integer sum;
/**
* 编写算法,计算下面表达式的值
* 1 + (1+2 + 1*2)+ (1+2+3 + 1*2*3) +...+ (1+2+...+n + 1*2*...*n)
* 1
* 1 + 5 = 6
* 1 + 5 + 12 = 18
* 1 + 5 + 12 + 34 = 52
* 1 + 5 + 12 +34 + 135 = 187
*/
public static Integer countSum(int n){
sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * (n - i + 1) + (i == 1 ? 0:recursion(i));
}
return sum;
}
public static Integer recursion(int n){
if(n == 1){
return 1;
}
return n*recursion(n-1);
}
public static void main(String[] args) {
System.out.println("3 :" + countSum(3));
System.out.println("4 :" + countSum(4));
System.out.println("5 :" + countSum(5));
System.out.println("6 :" + countSum(6));
System.out.println("7 :" + countSum(7));
}
}
验证结果:
3 :18
4 :52
5 :187
6 :928
7 :5996