Find GCD of two numbers using for loop and if statement
public class GCD {

public static void main(String[] args) {

int n1 = 81, n2 = 153, gcd = 1;

for(int i = 1; i <= n1 && i <= n2; ++i)
{
// Checks if i is factor of both integers
if(n1 % i==0 && n2 % i==0)
gcd = i;
}

System.out.printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}
}

When you run the program, the yield will be:

G.C.D of 81 and 153 is 9

Here, two numbers whose GCD are to be found are put away in n1 and n2 separately.

At that point, a for circle is executed until the point when I is not exactly both n1 and n2. Along these lines, all numbers among 1 and littlest of the two numbers are iterated to discover the GCD.

In the event that both n1 and n2 are divisble by I, gcd is set to the number. This goes ahead until the point that it finds the biggest number (GCD) which partitions both n1 and n2 without leftover portion.

Find GCD of two numbers using while loop and if else statement
public class GCD {

public static void main(String[] args) {

int n1 = 81, n2 = 153;

while(n1 != n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}

System.out.println("G.C.D = " + n1);
}
}

Java Program to Generate Multiplication Table

When you run the program, the yield will be:

G.C.D = 9

This is a superior method to discover the GCD. In this technique, littler whole number is subtracted from the bigger number, and the outcome is alloted to the variable holding bigger number. This procedure is proceeded until the point when n1 and n2 are equivalent.

The over two projects fills in as expected just if the client enters positive whole numbers. Here's a little adjustment of the second model to discover the GCD for both positive and negative whole numbers.

GCD for both positive and negative numbers
public class GCD {

public static void main(String[] args) {

int n1 = 81, n2 = -153;

// Always set to positive
n1 = ( n1 > 0) ? n1 : -n1;
n2 = ( n2 > 0) ? n2 : -n2;

while(n1 != n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}

System.out.println("G.C.D = " + n1);
}
}

When you run the program, the output will be:

G.C.D = 9

How to Improve the Performance of a Java Application