打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java实现阶1!+2!+3!+...+30!
方法1:
import java.math.BigInteger;

public class One {
  public static void puls(int temp){
    BigInteger proccut = BigInteger.ONE;
    
    BigInteger sum[] = new BigInteger[temp];
    BigInteger finalSum = BigInteger.ZERO;
    while(temp>=1){
      for (int j = 1; j <= temp; j++) {
         BigInteger t = new BigInteger(Integer.toString(j));
         proccut = proccut.multiply(t);
      }
      //System.out.println(temp+"的阶乘是:"+proccut);
      sum[temp-1] = proccut;
      proccut = BigInteger.ONE;
      temp--;
    }
    for (int i = 0; i < sum.length; i++) {
      //System.out.println("sum["+i+"]:"+sum[i]+"\t");
      finalSum = finalSum.add(sum[i]);
    }
    
    System.out.println("阶乘的和是:"+finalSum);
  }
  public static void main(String[] args) {
    puls(30);
  }
}

方法2:
import java.math.BigDecimal;

public class Two{

 /**
  * @param args
  */
 public static void main(String[] args) {
 String sum="1";
 
 for(int i=1;i<=30;i++){
  String s="1";
  //计算某个数的阶乘
  for(int j=1;j<=i;j++){
   BigDecimal str= new BigDecimal(s);
   BigDecimal end= new BigDecimal(j);
   BigDecimal re=end.multiply(str);
   s=re.toString();
  }
  //把1--30的阶乘加起来
  BigDecimal str= new BigDecimal(sum);
  BigDecimal end= new BigDecimal(s);
  BigDecimal re=end.add(str);
  sum=re.toString();
 }
      System.out.println("1!+2!+3!+..+30!的结果为:"+sum);//打印结果为274410818470142134209703780940314
 }

}

方法3:(这种会丢失精度)
public class Three {
public static void main(String[] args){
double mul=0;
double array[] = new double[30];
for(int i=1;i<=array.length;i++){
mul=multiply(i);
array[i-1] = mul;
}
System.out.println("1!+2!+3!+...+30!=" + sum(array));
}
public static double multiply(int x){
if(x==1){
return 1;
}else{
return x*multiply(x-1);
}
}
public static double sum(double array[]){
double s=0;
for(int i=0;i<array.length;i++){
s += array[i];
}
return s;
}
}

方法4:(这种是用来求某个数的阶乘)
public class Four {
public static void main(String[] args){
int i,j,n,carry;
int digit = 1;
System.out.println("请输入一个正整数:");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int[] array = new int[500];
array[0] = 1;
for(i=2;i<=n;i++){
for(j=0,carry=0;j<digit;j++){
int temp = i * array[j] + carry;
array[j] = temp % 10;
carry = temp / 10;
}
while(carry !=0){
digit++;
array[digit-1] = carry % 10;
carry = carry / 10;
}
}
System.out.print(n + "!=");
for(i=digit;i>0;i--){
System.out.print(array[i-1]);
}
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
JAVA大数处理(BigInteger,BigDecimal)
Java常用类库(二)
API
Java学习_Java核心类
Java基础之:大数
JAVA求百分比
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服