简体   繁体   中英

Factorial program not giving correct output

I have made the following program to calculate the factorial of n integers using BigInteger in Java, but it is always giving 1 as the result. Where is the mistake?

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
        }
    }
}

BigInteger is immutable. The result of [BigIteger].mutlipy([BigInteger]) needs to be reassigned to get desired output like:

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

The result should be printed after performing the operation in the while loop. Look at this modified code:

  key=Integer.parseInt(br.readLine());
  while(key>0){
       result = result.multiply(BigInteger.valueOf(key));
       key--;
  }
  System.out.println(key+" "+result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM