首页 > 编程知识 正文

1到100的阶乘和是多少,for循环计算100的阶乘

时间:2023-05-06 03:46:09 阅读:272518 作者:2920

100阶乘问题是经常面试问道的问题,

先来一段用加法计算的代码:

public class FactorialInAddition { public static void main(String[] args) { for(int i=1;i<=100;i++){ System.out.println(factorial(i)); } } public static String factorial(int n){ if(n<=0){ return null; } String result="1"; String tmp="0"; for(int i=2;i<=n;i++){ for(int j=0;j<i;j++){ //I write 'BigIntegerAddition' in my own BigIntegerAddition.java tmp=BigIntegerAddition.add(result, tmp);//String add(String,String) } result=tmp; tmp="0"; } return result; } }

这个问题的实质性问题是如何解决越界的问题,100阶乘要远远超过int的最大值;

但java已经有解决方案了,那就是BigInteger,先看看其成员就知道其数据结构是怎么设计的了。

final int signum; //正负符号,有三个值-1,0和1 final int[] mag;  //值大小,是一个int[]数组

所以回答此问题也是用数组的形式进行解决数据大的问题。可以使用类似byte[],int[],char[],long[]。肯定推荐用int[]或byte[]。

实现代码:

public class Test{ private int[] value = {1}; private boolean seg=true; public static void main(String[] args) throws Exception{ Test clas = new Test(); System.out.println(clas.factorial(100)); } private String factorial(int n){ if (n<=0) return "输入值必须为正数"; for (int i=1; i<=n; i++) { int length = value.length; int index = 0; //当前值索引值 int temp = 0; do { if(temp!=0) extendValue(index); //判断扩容 int currentValue = value[index]; temp = i * currentValue + temp; value[index] = temp % 10; temp = temp / 10; index++; }while(!(temp==0 && index==value.length)); } StringBuffer stringBuffer = new StringBuffer(); for(int i=value.length-1;i>=0;i--){ stringBuffer.append(String.valueOf(value[i])); //缺少删除字符串前面多余的0 } return stringBuffer.toString(); } private void extendValue(int index){ if (index==this.value.length){ int[] newValue = new int[this.value.length*2]; System.arraycopy(this.value,0,newValue,0,value.length); this.value=newValue; } }}

 

转载于:https://www.cnblogs.com/parent-absent-son/p/10133442.html

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。