阶乘 计数100的阶乘,结果取近似值或者精确值都可以java程序实现 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 public static void main(String[] args){ Scanner scan=new Scanner(System.in); System.out.println("请输入一个整数:"); long n=scan.nextLong(); long sum=1; for(long i=1;i<=n;i++){ sum*=i; } System.out.println("n的阶乘是:"+sum);} 要的是100的 结果会超出long的范围 import java.math.BigInteger;import java.util.ArrayList; public class NewClass { protected static ArrayList alist = new ArrayList(); static { alist.add(BigInteger.valueOf(1)); } /** * Creates a new instance of factorial */ public static synchronized BigInteger factorial(int x) { if (x < 0) { throw new IllegalArgumentException("x must be non-negative."); } for (int size = alist.size(); size <= x; size++) { BigInteger lastfact = (BigInteger) alist.get(size - 1); BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size)); alist.add(nextfact); } return (BigInteger) alist.get(x); } public static void main(String[] args) { System.out.println("100 != " + factorial(100)); }} run:100 != 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000成功生成(总时间:1 秒) 三种方法可以取返回long类型的疑问 java插入oracle数据库问题 为什么conn.setAutoCommit(false)不起作用? 如何改改变CustomerItem焦点 关于窗口自动粘合的 求助java的小数循环程序 一个jtable外观的问题 急问:为什么加载图片后,菜单不能显示 请教高手关于集合类的问题,在线等。 如何通过外部的代码在JFrame上画图 通过java代码执行start.bat的问题,求指点 Java变量定义
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
System.out.println("请输入一个整数:");
long n=scan.nextLong();
long sum=1;
for(long i=1;i<=n;i++){
sum*=i;
}
System.out.println("n的阶乘是:"+sum);
}
import java.math.BigInteger;
import java.util.ArrayList;
public class NewClass { protected static ArrayList alist = new ArrayList(); static {
alist.add(BigInteger.valueOf(1));
} /**
* Creates a new instance of factorial
*/
public static synchronized BigInteger factorial(int x) {
if (x < 0) {
throw new IllegalArgumentException("x must be non-negative.");
}
for (int size = alist.size(); size <= x; size++) {
BigInteger lastfact = (BigInteger) alist.get(size - 1);
BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
alist.add(nextfact);
}
return (BigInteger) alist.get(x);
} public static void main(String[] args) {
System.out.println("100 != " + factorial(100));
}
}
100 != 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
成功生成(总时间:1 秒)