package cn.sdut.test;
import java.math.BigInteger;
/*
* 求到20阶乘的和 以及 求到21阶乘的和
*/
public class Test04 {
public static void main(String[] args) {
int n =21;
biginteger(n);
longtype(n);
System.out.println(Long.MAX_VALUE);
//long x = 1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20;//会溢出
long x = 1L*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20;//不会溢出System.out.println("x="+x);
}private static void longtype(int n) {long sum = 0;long value =1;for(int i = 1;i<=n;i++){value*=i;sum+=value;}System.out.println(sum);}private static void biginteger(int n) {BigInteger sum = new BigInteger("0");BigInteger value = new BigInteger("1");for(int i =1;i<=n;i++){BigInteger temp = new BigInteger(i+"");value =value.multiply(temp);sum =sum.add(value);}System.out.println(sum.toString());}}

本文介绍了一种使用Java实现计算20和21阶乘的和的方法,通过BigInteger类来处理大数运算,避免了数值溢出的问题,并提供了long类型的对比计算。
7825

被折叠的 条评论
为什么被折叠?



