Java
import java.util.Scanner;
public class Main {
private static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.println("GCD = " + gcd(a, b));
sc.close();
}
}Output
Enter first number: 24 Enter second number: 36 GCD = 12
We repeatedly replace (a, b) with (b, a % b) until b becomes 0.