0

我已经制作了以下程序来使用 Java 中的 BigInteger 计算 n 个整数的阶乘,但它总是给出 1 作为结果。错误在哪里?

import java.math.BigInteger;
import java.io.*;

class Factorial
{
    public static void main(String args[])
    {
        try
        {
            int key;
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            BigInteger result=new BigInteger("1");
            //take the quantity of elements for which factorial is to be calculated
            int num=Integer.parseInt(br.readLine());

            while(num-->0)
            {
                //input the number for which factorial is to be calculated
                key=Integer.parseInt(br.readLine());
                while(key>0)
                {
                    System.out.println(key+""+result);
                    result.multiply(BigInteger.valueOf(key));
                    key--;
                }
                //again make the result back to 1 for next key element
                result=new BigInteger("1");
            }
        }catch(Exception e)
        {
            //do nothing
        }
    }
}
4

1 回答 1

2

BigInteger是不可变的。[BigIteger].mutlipy([BigInteger])需要重新分配结果以获得所需的输出,例如:

  result = result.multiply(BigInteger.valueOf(key));

执行 while 循环中的操作后,应打印结果。看看这个修改后的代码:

  key=Integer.parseInt(br.readLine());
  while(key>0){
       result = result.multiply(BigInteger.valueOf(key));
       key--;
  }
  System.out.println(key+" "+result);
于 2013-10-05T14:45:57.597 回答