public class GcdOfTwoNumbers
{
public static void main(String[] args)
{
int no1 = 12, no2 = 15;
int gcd = 1;
for (int i = 1; i <= no1 && i <= no2; i++)
{
if (no1 % i == 0 && no2 % i == 0)
{
gcd = i;
}
}
System.out.println("GCD: " + gcd);
}
}
GCD: 3
import java.util.Scanner;
public class GcdOfTwoNumbers
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter no1: ");
int no1 = scanner.nextInt();
System.out.print("Enter no2: ");
int no2 = scanner.nextInt();
int gcd = 1;
for (int i = 1; i <= no1 && i <= no2; i++)
{
if (no1 % i == 0 && no2 % i == 0)
{
gcd = i;
}
}
System.out.println("GCD: " + gcd);
}
}
Enter no1: 56 Enter no2: 72 GCD: 8
no1
and no2
, from the user.
for
loop runs from 1 to the smaller of no1 and no2.
i
.
i
, assign i
to the gcd variable (update it with the latest common divisor).
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.