简体   繁体   中英

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?

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

It has not been proposed but you may also think of using the import static to lighten up your code and also the method BigInteger#mod instead of #remainder

import java.math.BigInteger;
import static java.math.BigInteger.valueOf;


public class BigInt {
    public static void main(String[] args) {
        System.out.println(testMod(5,36)); // 13
        System.out.println(testMod(250, 999)); // 160
    }

    public static int testMod(int a, int mod) {
        return valueOf(a).pow(4).mod(valueOf(mod)).intValue();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM