在java中计算数字大于int和long的阶乘?

时间:2012-09-30 13:00:02

标签: java biginteger factorial

在这里搜索和谷歌几天以及询问我的编程朋友。 不幸的是,我仍然不明白如何更改我的代码...

我的程序计算给定数字的阶乘。然后它提供一个数字,表示阶乘回答包括多少位数。然后它将这些数字的值相加,得出总数。

我的程序适用于1之间的任何数字!和31!...如果你输入超过31! (例如50!或100!)它不起作用,只丢回数字而不是总数。

我希望你们能指出我正确的方向或给我一些建议。 我明白使用BigIntegers可能是一个解决方案,但我个人并不理解,因此来到这里。

非常感谢任何帮助。感谢。

    package java20;

    /**
    * Program to calculate the factorial of a given number.
    * Once implemented, it will calculate how many digits the answer includes.
    * It will then sum these digits together to provide a total.
     * @author shardy
     * date: 30/09/2012
     */

    //import java.math.BigInteger;
    public class Java20 {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

    //Using given number stored in factorialNo, calculates factorial
    //currently only works for numbers between 1! and 31! :(
        int fact= 1;
        int factorialNo = 10;

        for (int i = 1; i <= factorialNo; i++)
            {
               fact=fact*i;
            }

        System.out.println("The factorial of " + factorialNo + 
                " (or " + factorialNo + "!) is: " + fact);

        //Using answer stored in fact, calculates how many digits the answer has
        final int answerNo = fact;
        final int digits = 1 + (int)Math.floor(Math.log10(answerNo));

        System.out.println("The number of digits in the factorials "
                + "answer is: " + digits);        

        //Using remainders, calculates each digits value and sums them together
        int number = fact;
        int reminder;
        int sum = 0;

        while(number>=1)
            {
             reminder=number%10; 
             sum=sum+reminder;
             number=number/10;
            }

        System.out.println("The total sum of all the " + digits 
                + " idividual digits from the answer of the factorial of " 
                + factorialNo + " is: " + sum);

      }
    }

3 个答案:

答案 0 :(得分:3)

你可以在java中使用BigInteger,它有你想要的数量

    BigInteger fact= BigInteger.ONE;
    int factorialNo = 10;

    for (int i = 2; i <= factorialNo; i++){
      fact = fact.multiply(new BigInteger(String.valueOf(i)));
    }

    System.out.println("The factorial of " + factorialNo +
                                " (or " + factorialNo + "!) is: " + fact);
   final int digits = fact.toString().length();

   BigInteger number = new BigInteger(fact.toString());
   BigInteger reminder;
   BigInteger sum = BigInteger.ZERO;
   BigInteger ten = new BigInteger(String.valueOf(10));

   while(number.compareTo(BigInteger.ONE)>=0)
     {
     reminder=number.mod(ten);
     sum=sum.add(reminder);
     number=number.divide(ten);
     }

     System.out.println("The total sum of all the " + digits
                     + " idividual digits from the answer of the factorial of "
                     + factorialNo + " is: " + sum

编辑:代码经过改进,与作者代码兼容

答案 1 :(得分:1)

  

如果你输入超过31的东西! (例如50!或100!)它没有   工作,只是减去数字而不是总数。

这是因为当您超出其最大可能值时,原始整数类型将受overflow的约束。哪些计算因子有倾向。

  

我希望你们能指出我正确的方向或给我   一些忠告。据我所知,使用BigIntegers可能是一个解决方案   不要亲自理解他们,因此来到这里。

您是正确的,使用BigInteger是一种可能的解决方案。例如,您可以执行以下操作:

public BigInteger factorial(int num) {
    if (num < 0) {
        throw new IllegalArgumentException("Not today!");
    }

    BigInteger result = BigInteger.ONE;

    for (int next = 2; next <= num; next++) {
        result = result.multiply(new BigInteger(Integer.toString(next, 10)));
    }

    return result;
}

答案 2 :(得分:0)

如果你正在计算像(m!/ n!)这样的东西,你最好使用因子的对数。

您还应该考虑这两项改进:

  1. 记住,不要重新计算。计算后,请存储这些来之不易的值。
  2. 您应该使用gamma function来计算阶乘。你通过循环这样做的方式是向学生展示的天真之物。 Numerical Recipes中有ln(gamma(x))的良好实施。
  3. 如果必须,您可以随时使用BigDecimal,但这是最后的手段。你仍然应该考虑这些要点。

    Apache Commons提供了一个伽玛函数实现。源代码可能不像天真的方法那么熟悉,但是如果你看到它是如何完成的,那么即使对于温和的论证它也会更加有效。