求1到20的阶乘的和 以及 1到21的阶乘的和,使用long和BigInteger

来源:互联网 发布:关于套路的网络用语 编辑:程序博客网 时间:2024/05/16 08:53
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());}}

原创粉丝点击