Working with BigInteger bypassing Integer.toString ()

I want to get the remainder of the fourth power of the 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 converting to String seems unnecessary, and using the operator %will be more concise than a.remainder(b). Can I rewrite it to make it more understandable?

+4
source share
3 answers

String, BigInteger.valueOf(long), int BigInteger. % BigInteger. , BigInteger.remainder() . , @LouisWasserman, BigInteger.modPow() .

, BigInteger , . , , , :

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

, , String :

static int testMod(int a, int mod)
{
    BigInteger a4 = BigInteger.valueOf(a).pow(4);

    return a4.remainder(BigInteger.valueOf(mod)).intValue();
}
+3

, import static, , BigInteger#mod #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();
    }
}
+1

All Articles