Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
sixtytrees Avatar asked Jan 06 '23 19:01

sixtytrees


2 Answers

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();
}
like image 90
John Bollinger Avatar answered Jan 14 '23 17:01

John Bollinger


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();
}
like image 20
Sean Bright Avatar answered Jan 14 '23 18:01

Sean Bright