[英]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)
. 它工作正常,但转换为String似乎是不必要的,使用%
运算符将比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
. 您可以通过使用BigInteger.valueOf(long)
将int
转换为BigInteger
来消除通过String
的转换。 You cannot apply the %
operator to BigInteger
operands, however. 但是,您不能将%
运算符应用于BigInteger
操作数。 If you could, then BigInteger.remainder()
would not exist. 如果可以,那么BigInteger.remainder()
将不存在。 On the other hand, as @LouisWasserman observes, there is BigInteger.modPow()
to perform the exponentiation and remainder in one call. 另一方面,正如@LouisWasserman所观察到的那样,有一个BigInteger.modPow()
来执行一次调用中的取幂和余数。
Additionally, BigInteger
supports method chaining, as you recognize. 此外,正如您BigInteger
, BigInteger
支持方法链接。 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: 我不知道这是否更好,但它摆脱了不必要的转换为String
并返回:
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 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.