How to calculate the GCD (Greatest Common Divisor) in Java

by Dinesh Thakur Category: Control Structures

Currently the definition of Greatest Common Divisor (GDC) can be formalized as well:

Let a, b and c nonzero integers, we say that c is a common divisor of a and b to c divides (write c | a) and c divides b (c | b). We call D (a, b) the set of all common divisors of a and b.

The code snippet below shows how to calculate the GDC two reported numbers:

```import java.util. *;

public class ProgGCD {

public static void main (String [] args) {

Scanner scan = new Scanner (System.in);

System.out.print ("Calculate the Greatest Common Divisor (GCD)\n");

System.out.print ("Enter the first number :");

int First_No = scan.nextInt();

System.out.print ("Enter the second number :");

int Second_No = scan.nextInt();

System.out.println ("The GCD of " + First_No + " and " + Second_No + " and " + GDC (First_No, Second_No));

}

public static int GDC (int x, int y) {

int result;

while (y != 0) {

result = x% y;

x = y;

y = result;

}

return x;

}

}

```

About Dinesh Thakur

Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles