Java Program to Calculate the GCD of Two Numbers

In this example, we are giving a program to calculate the GCD(greatest common divisor) of two numbers.


To calculate the GCD:

  1. # To calculate the GCD
  2. public class GCD {
  3. public static void main(String[] args) {
  4. int n1 = 49, n2 = 7, gcd = 1;
  5. for(int i = 1; i <= n1 && i <= n2; ++i) {
  6. if(n1 % i==0 (n1 % i==0)
  7. gcd = i;
  8. }
  9. System.out.printf("G.C.D of %d and %d is %d", n1, n2, gcd);
  10. }
  11. }

Output:

G.C.D of 49 and 7 is 7