苦苦挣扎,了解这段代码如何输出Euclid算法

时间:2015-11-20 17:42:06

标签: java algorithm

我正在尝试编写Euclids算法的代码,我在网上发现了一些代码,它输出了两个数字的最大公约数。这是

else {
    return gcd(b, a % b);
}

然而,我不太明白它是如何让我得到最大的除数。我理解Euclid的算法如何在纸上工作但不是这个。 在我看来,上面的代码应该返回b的模数a,所以如果“a”是1071而“b”是462,它将返回147但是上面的代码返回21. <code>gcd(b, a % b);中的第一个b如何影响输出?

以下是整个代码:

package algorithms;
import java.util.Scanner;
public class Question3 {
    private static Scanner input=new Scanner(System.in);
    public static void main(String[] args) {


    //simple input statements to get the numbers of the user
    System.out.print("Please input the first number to be worked on= ");
    double a=input.nextDouble();
    System.out.print("Please input the second number to be worked on= ");
    double b=input.nextDouble();

    //call the method in which the calculations are done
    double commondiv=gcd(a,b);


    //print out the the common divisor
    System.out.print("The Common Divisor of "+ a +" and "+ b + " is "+commondiv);
    //System.out.print(b);
}
public static double gcd(double a, double b){
    //an if statement will allow for the program to run even if
    //a is greater than b
    if (a>b){
        //if the input b is equal to zero
        //then the input a will be returned as the output
        //as the highest common divisor of a single number is itself
        if (b == 0){

            return a;
        }
        //this returns the greatest common divisor of the values entered
        else{
            return gcd(b, a % b);
        }
    }
    else if (a<b){
        if (a == 0){

            return b;
        }
        else{
            return gcd(a, b % a);
        }

    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

请参阅以下说明了解迭代:

在第一次迭代中 a = 1071,b = 462

  1. a&gt; b所以
    gcd(b,a%b)是gcd(462,147)

  2. 同样a> b为真a = 462,b = 147所以
    gcd(147,21)

  3. a&gt; b为a = 147,b = 21因此为真 gcd(21,0)

  4. a&gt; b为a = 21,b = 0 现在b == 0是真的 返回一个即21