Question

I want to calculate factorial my code at present is this:

else if(btn.getText().equals("x!"))
    {
        double LeftVal = Double.parseDouble(currentInput);
        double result = Double.NaN;
        if(currentInputLen > 0 && LeftVal >0)
        {
            result = Factorial(LeftVal);
        }

        resultText.setText(result+"");
    }

code to calculate factorial is this:

private double Factorial(double input)
{
    double output=input;
    for(int i=(int) (input-1);i>0;i--)
    {
        output*=i;
    }

    return output;
}

I imported java.math.*; and changed my code to this:

else if(btn.getText().equals("x!"))
    {
        BigInteger LeftVal = BigInteger(currentInput);
        BigInteger result = 0;
        if(currentInputLen > 0 && LeftVal >0)
        {
            result = Factorial(LeftVal);
        }

        resultText.setText(result+"");
    }

and factorial method to this

private BigInteger Factorial(BigInteger input)
{
    BIgInteger output=input;
    for(int i=(int) (input-1);i>0;i--)
    {
        output*=i;
    }

    return output;
}

I saw on android developer site that BigInteger(string) will convert that string to big integer but that does not work and shows error also there were errors on using regular mathematical errors.

The reason i want to use big integer is because if i calculate 12! using double it shows answer in scientific form with e raised to power something i want exact answer.

Was it helpful?

Solution

For your factorial method using BigInteger you could use:

private BigInteger factorial(BigInteger input) {
    BigInteger output = input;
    for (BigInteger i = input.subtract(BigInteger.ONE); i.compareTo(BigInteger.ZERO) > 0; i = i.subtract(BigInteger.ONE)) {
        output = output.multiply(i);
    }
    return output;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top