java - BigInteger 模数不是正数
问题描述
public static BigInteger primeFactorOf(BigInteger n) {
BigInteger p = n.sqrt();
BigInteger small = new BigInteger("0");
BigInteger two = new BigInteger("2");
while(n.mod(p).compareTo(small)!=0){
p=p.subtract(two);
}
System.out.println(p);
System.out.println(n.divide(p));
return p;
}
public static void main(String[] args){
BigInteger big = new BigInteger("3223956689869297");
primeFactorOf(big);
}
得到
Exception in thread "main" java.lang.ArithmeticException: BigInteger: modulus not positive
at java.base/java.math.BigInteger.mod(BigInteger.java:2692)
at matma.primeFactorOf(matma.java:125)
at matma.main(matma.java:136)
我做了这个函数来分解两个素数的大数(在这种情况下82192031*39224687=3223956689869297
)。
虽然该函数适用于较小的数字(当素数为 6 位时),但现在当我使用 8 位素数时出现此错误。
我不明白它以前为什么以及如何工作,现在却不行。
解决方案
这是因为 sqrt(3223956689869297) 是偶数。3223956689869297的质数因子都是奇数。当您每次下降 2 时,您只查看偶数,并跳过主要因素。最终,模数 (p) 从 2 变为 0,您会得到这个错误(模数不是正数)。
推荐阅读
- html - 如何使用 CSS 网格将 textarea 扩展到 2 行?
- android - Android上的sqlite中的“WHERE IN”子句是否有任何限制?
- php - Gmail API - ListUsersLabels - 没有邮件总数
- android - 如何通过电话知道当前或不以编程方式
- reactjs - 测试异步获取数据的 React 组件
- python - 在当前目录中找不到文件的 VSCode 文件
- php - 通过phpword中的链接通过数据库导入图像时出错
- android - 对话框片段中的按钮是不可见的,但为什么呢?
- javascript - Webpack 只加载由 css 引用的图像。不加载js引用的图片
- java - PageParameters 导致多次调用 Page 的 onConfigure