1!+2!+----+100!阶乘求和

来源:互联网 发布:模拟炒股 app 知乎 编辑:程序博客网 时间:2024/05/21 14:46
求阶乘要用BigInteger.
Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.math.BigInteger;
 
public class Test1 {
    public static void main(String[] args) {
        BigInteger sum = new BigInteger("0");
        for (int i = 1; i <= 100; 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;
    }
}
http://blog.csdn.net/w00w12l/article/details/7290750
bigInteger常用技巧。


public class jiechen {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 1;
int k = 1;
int sum = 0;
for(i = 1; i <= 5; i++){
k *= i;
sum += k;
}
System.out.println("1!+2!+3!+4!+5!="+sum);
}
}
小数量的直接使用递增。
注意int 等范围

字节型 byte -128-127 0

字符型 char 16 ‘\u000’-\uffff ‘\u0000’

短整型 short 16 -32768-32767 0

整型 int 32 -2147483648,2147483647 0

长整型 long 64 -9.22E18,9.22E18 0

浮点型 float 32 1.4E-45-3.4028E+38 0.0

双精度型 double 64 4.9E-324,1.7977E+308 0.0



0 0
原创粉丝点击