繁体   English   中英

使用BigInteger遵循算法

[英]Using BigInteger to follow algorithm

我尝试遵循在https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm上给出的伪代码。 这适用于int值,但是,当我尝试实现相同的代码时,除了使用BigInteger而不是ints之外; 它似乎从未退出过循环吗? 它永远不会到达打印语句,并将继续运行。 这对我来说是零意义,因为可以工作的int实现与类型完全相同。 有人注意到我在做什么吗? 它应该可以工作= /无关紧要,无论我使用哪个测试值,它都会运行,但会继续运行,并且永远不会到达print语句。

public void extended_gcd(BigInteger a, BigInteger b)
{
    BigInteger[] ans = new BigInteger[3];
    BigInteger[] ans1 = new BigInteger[3];
    //s
    ans[0] = BigInteger.valueOf(0);
    //t
    ans[1] = BigInteger.valueOf(1);
    //r
    ans[2] = b;

    //old s
    ans1[0] = BigInteger.valueOf(1);
    //old t
    ans1[1] = BigInteger.valueOf(0);
    //old r
    ans1[2] = a;

    while (!ans[2].equals(0)){
    BigInteger quotient = ans1[2].divide(ans[2]);

    BigInteger temps = ans[0];
    BigInteger tempt = ans[1];
    BigInteger temptr =ans[2];

    ans[2] = ans1[2].subtract(quotient).multiply(temptr);
    ans1[2] = temptr;

    ans[0] = ans1[0].subtract(quotient).multiply(temps);
    ans1[0] = temptr;

    ans[1] = ans1[1].subtract(quotient).multiply(tempt);
    ans1[1] = temptr;

    }

    System.out.println("Bézout coefficients:" + ans1[0] + "," + ans1[1]);
   // System.out.println( "greatest common divisor:", old_r);
   // System.out.println( "quotients by the gcd:", (t, s));
}

我的猜测是while循环的谓词永远不会满足:

while (!ans[2].equals(0)){

尝试与BigInteger.ZERO比较,看看是否有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM