sixtytrees sixtytrees - 5 months ago 8
Java Question

Working with BigInteger bypassing Integer.toString()

I want to get a remainder of a fourth power of a number. Here is my code:

static int testMod(int a, int mod) {

/* //This looks clear
BigInteger a4 = a;
return (a4.pow(4))%mod;
*/

//This works
String a2String = Integer.toString(a);
String mod2String = Integer.toString(mod);
BigInteger a4 = new BigInteger(a2String);
BigInteger modBigInt = new BigInteger(mod2String);
a4 = a4.pow(4);

return a4.remainder(modBigInt).intValue();
}


It works fine, but the conversion to String seems unnecessary, and using the
%
operator would be more concise than
a.remainder(b)
. Is it possible to rewrite it to make it more clear?

Answer

You can get rid of the conversions through String by using BigInteger.valueOf(long) to convert your ints to BigInteger. You cannot apply the % operator to BigInteger operands, however. If you could, then BigInteger.remainder() would not exist. On the other hand, as @LouisWasserman observes, there is BigInteger.modPow() to perform the exponentiation and remainder in one call.

Additionally, BigInteger supports method chaining, as you recognize. You could do the whole thing in one statement if you wanted, but I think this is a good compromise between concision and readability:

static int testMod(int a, int mod) {
    BigInteger bigA = BigInteger.valueOf(a);
    BigInteger bigMod = BigInteger.valueOf(mod);

    return bigA.modPow(BigInteger.valueOf(4), bigMod).intValue();
}