我想弄清楚为什么以下没有正确计算
x = Math.pow(w,e);
当我用Java计算它时,我得到1075,但我应该得到779。
int e = 17;
int w = 803;
int n = 2773;
double x = 0;
x = Math.pow(w,e) % n;
System.out.println(x);
答案 0 :(得分:3)
double
浮点数具有53位精度,这不足以存储像803 17 这样的大数的精确值。要在Java中进行模幂运算,可以在BigInteger
上使用modPow
方法。
答案 1 :(得分:2)
As(803 ^ 17)是一个非常大的数字,因此您必须将BigInteger数据类型用于此处使用的变量,而不是int或double数据类型。我们不能将整数或双变量转换为BigInteger变量。
所以,该计划将是:
import java.math.BigInteger;
public class JavaPow {
public static void main(String[] args)
{
BigInteger e = new BigInteger("17");
BigInteger w = new BigInteger("803");
BigInteger n = new BigInteger("2773");
BigInteger x;
x = w.modPow(e,n);
System.out.println(x);
}
}