# How to calculate the GCD (greatest common divisor) of two numbers in Java

```package javaapplication1;

public class JavaApplication1 {

public static void main(String[] args) {

int a = 12, b = 20, gcd = 0;

for (int i = 1; i <= a && i <= b; i++)
{
if (a % i == 0 && b % i == 0)
gcd = i;
}

System.out.format("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd);
}
}

/*
run:

The GCD (greatest common divisor) of 12 and 20 is: 4

*/```

```package javaapplication1;

public class JavaApplication1 {

public static void main(String[] args) {

int a = 12, b = 20, gcd = 0;

int i = a < b ? a : b;

for (;i <= a && i <= b; i--)
{
if (a % i == 0 && b % i == 0)
{
gcd = i;
break;
}
}

System.out.format("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd);
}
}

/*
run:

The GCD (greatest common divisor) of 12 and 20 is: 4

*/```

```package javaapplication1;

public class JavaApplication1 {

public static void main(String[] args) {

int a = 12, b = 20;

System.out.format("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd(a, b));
}
static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
}

/*
run:

The GCD (greatest common divisor) of 12 and 20 is: 4

*/```