2015-11-20 2 views
0

Я пытался написать код алгоритма Евклида, и я нашел некоторый код онлайн, который выработал наибольший общий делитель для двух введенных чисел. ЗдесьБорясь, чтобы понять, как этот код выводит алгоритм Евклида

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

Однако, я не совсем понимаю, как он получает от меня наибольший общий делитель. Я понимаю, как алгоритм Евклида работает на бумаге, но не это. На мой взгляд, приведенный выше код должен вернуть модуль a из b, поэтому, если «a» было 1071, а «b» - 462, оно вернет 147, однако приведенный выше код возвращает 21. Как первый b в <code>gcd(b, a % 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; 
} 
+3

это рекурсивная. –

+0

Если бы были 1071 и b были 462, он возвратил бы gcd из 462 и 147. –

ответ

1

Пожалуйста Смотрите следующее объяснение итераций:

В первую итерацию
а = 1071 б = 462

  1. а> Ь поэтому
    gcd (b, a% b), который является gcd (462,147)

  2. Снова а> Ь справедливо как = 462, B ​​= 147, так
    НОД (147,21)

  3. а> Ь справедливо как = 147, B = 21, так
    НОД (21,0)

  4. а> Ь справедливо как = 21, б = 0 Теперь Ь == 0 верно Вернуть т.е. 21

+0

Думаю, что теперь я понимаю, ваш комментарий заставило меня понять, что вывод можно рассматривать как возвращение gcd (b) (a% b). По какой-то причине я думал об этом как gcd (b, a%, b)! –