Java Program to Find GCD of two Numbers
Example 1: Find GCD of two numbers using for loop and if statement
class Main {
public static void main(String[] args) {
// find GCD between n1 and n2
int n1 = 81, n2 = 153;
// initially set to gcd
int gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// check if i perfectly divides both n1 and n2
if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}
System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd);
}
}
Example 2: Find GCD of two numbers using while loop and if else statement
class Main {
public static void main(String[] args) {
// find GCD between n1 and n2
int n1 = 81, n2 = 153;
while(n1 != n2) {
if(n1 > n2) {
n1 -= n2;
}
else {
n2 -= n1;
}
}
System.out.println("GCD: " + n1);
}
}
Example 3: GCD for both positive and negative numbers
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("GCD: " + n1);
}
}
Example 4: GCD of Two Numbers using Recursion
public class GCD {
public static void main(String[] args) {
int n1 = 366, n2 = 60;
int hcf = hcf(n1, n2);
System.out.printf("G.C.D of %d and %d is %d.", n1, n2, hcf);
}
public static int hcf(int n1, int n2)
{
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
}
Comments
Post a Comment