I want to use big integer in my android app but when ever i apply operators i get error?

StackOverflow https://stackoverflow.com/questions/22283892

  •  11-06-2023
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top