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?
You can get rid of the conversions through String
by using BigInteger.valueOf(long)
to convert your int
s 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();
}
I don't know if this is any better or not, but it gets rid of the unnecessary conversion to String
and back:
static int testMod(int a, int mod)
{
BigInteger a4 = BigInteger.valueOf(a).pow(4);
return a4.remainder(BigInteger.valueOf(mod)).intValue();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With