我想得到一个数字的剩余四次幂.这是我的代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但转换为String似乎是不必要的,使用%运算符将比更简洁a.remainder(b).是否可以重写它以使其更清晰?
您可以通过String使用BigInteger.valueOf(long)转换为ints来摆脱转换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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
229 次 |
| 最近记录: |