sixtytrees - 9 months ago 33

Java Question

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

`%`

`a.remainder(b)`

Answer

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();
}
```