日期:2014-05-20  浏览次数:20868 次

新手求解..1~30的阶乘求和 ,用方法编写 哪错了?
double sum = 1.00;
for(int i = 1; i <= 30; i++){
int num = F(a);
sum += num;
}
System.out.println("sum = " + sum);
}
public static double F(int num){
for(int i = 1; i <= num; i++){
int a = 1;
a = a * i;
}
return a;

------解决方案--------------------
求阶乘要用BigInteger,30!用long早就越界了
Java code

import java.math.BigInteger;

public class Test1 {
    public static void main(String[] args) {
        BigInteger sum = new BigInteger("0");
        for (int i = 1; i <= 30; i++) {
            sum = sum.add(getResult(i));
        }
        System.out.println("sum = " + sum);
    }

    public static BigInteger getResult(int num) {
        BigInteger result = new BigInteger("1");;
        for (int i = 1; i <= num; i++) {
            result = result.multiply(new BigInteger(String.valueOf(i)));
        }
        return result;
    }
}