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 に答える