Я пытался написать код алгоритма Евклида, и я нашел некоторый код онлайн, который выработал наибольший общий делитель для двух введенных чисел. ЗдесьБорясь, чтобы понять, как этот код выводит алгоритм Евклида
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;
}
это рекурсивная. –
Если бы были 1071 и b были 462, он возвратил бы gcd из 462 и 147. –