我正在使用BigInteger
实现费马分解算法,所以我可以分解。但目前,代码不起作用;它由于某种原因挂起。有人可以将我引导到问题所在,或者如果我的算法不正确,请告诉我吗? BigInteger
使生活变得困难,所以我不得不寻找平方根方法。
import java.math.BigInteger;
import java.util.Scanner;
public class Fermat
{
/** Fermat factor **/
public void FermatFactor(BigInteger N)
{
BigInteger a = sqrt(N);
BigInteger b2 = a.multiply(a).subtract(N);
while (!isSquare(b2)) {
a = a.add(a);
b2 = a.multiply(a).subtract(N);
}
BigInteger r1 = a.subtract(sqrt(b2));
BigInteger r2 = N.divide(r1);
display(r1, r2);
}
/** function to display roots **/
public void display(BigInteger r1, BigInteger r2) {
System.out.println("nRoots = "+ r1 +" , "+ r2);
}
/** function to check if N is a perfect square or not **/
public boolean isSquare(BigInteger N) {
BigInteger ONE = new BigInteger("1");
BigInteger sqr = sqrt(N);
if (sqr.multiply(sqr) == N || (sqr.add(ONE)).multiply(sqr.add(ONE)) == N)
return true;
return false;
}
public static BigInteger sqrt(BigInteger x)
throws IllegalArgumentException {
if (x.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Negative argument.");
}
// square roots of 0 and 1 are trivial and
// y == 0 will cause a divide-by-zero exception
if (x == BigInteger.ZERO || x == BigInteger.ONE) {
return x;
} // end if
BigInteger two = BigInteger.valueOf(2L);
BigInteger y;
// starting with y = x / 2 avoids magnitude issues with x squared
for (y = x.divide(two);
y.compareTo(x.divide(y)) > 0;
y = ((x.divide(y)).add(y)).divide(two));
if (x.compareTo(y.multiply(y)) == 0) {
return y;
} else {
return y.add(BigInteger.ONE);
}
} // end bigIntSqRootCeil
/** main method **/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Fermat Factorization Testn");
System.out.println("Enter odd number");
BigInteger N = scan.nextBigInteger();
Fermat ff = new Fermat();
ff.FermatFactor(N);
scan.close();
}
}
我知道我有很多错误,但任何帮助都是值得赞赏的。谢谢。
你的"for"循环:
for (y = x.divide(two);
y.compareTo(x.divide(y)) > 0;
y = ((x.divide(y)).add(y)).divide(two));
不会终止。也许你可以跟踪变量"y"的值,猜测什么时候必须停止。
编辑 :这是错误的(见评论)。问题出在生产线上
a = a.add(a)
内部程序费马因子。它应该是
a = a.add(ONE)
在我的机器中,我也在使用"A == B"测试等式时遇到了麻烦。方法"A.equals(B)"修复了它。