简体   繁体   English

使用BigInteger遵循算法

[英]Using BigInteger to follow algorithm

I tried following the pseudo code given on : https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm . 我尝试遵循在https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm上给出的伪代码。 This worked for int values, however when I tried to implement the same code except using BigInteger rather than ints; 这适用于int值,但是,当我尝试实现相同的代码时,除了使用BigInteger而不是ints之外; it doesn't ever seem to exit the loop? 它似乎从未退出过循环吗? it will never get to the print statement and will continue running. 它永远不会到达打印语句,并将继续运行。 This makes zero sense to me, as the int implementation which does work is identical except for the type. 这对我来说是零意义,因为可以工作的int实现与类型完全相同。 Anyone notice anything idiotic which I'm doing ? 有人注意到我在做什么吗? it should work =/ doesn't matter which test values I use, it will run but will just continue running and will never get to the print statement. 它应该可以工作= /无关紧要,无论我使用哪个测试值,它都会运行,但会继续运行,并且永远不会到达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));
}

My guess would be that the predicate for the while loop is never satisfied: 我的猜测是while循环的谓词永远不会满足:

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

Try comparing to BigInteger.ZERO and see if that helps. 尝试与BigInteger.ZERO比较,看看是否有帮助。

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

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