Algorithm
-
Input: Accept two integers, say
aandb, as input. -
Initialize Variables: Set variables
xandyto the values ofaandbrespectively. -
While Loop: Start a loop that continues until
ybecomes 0.- Inside the loop:
- Set a temporary variable
tempto the value ofy. - Update
yto be the remainder of the divisionxbyy. - Update
xto be the value oftemp.
- Set a temporary variable
- Inside the loop:
-
Output: The GCD is the non-zero value of
xwhen the loop terminates.
Code Examples
#1 Code Example- Find GCD of two numbers using for loop and if statement
Code -
Java Programming
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);
}
}
Copy The Code &
Try With Live Editor
Output
#2 Code Example- Find GCD of two numbers using while loop and if else statement
Code -
Java Programming
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);
}
}
Copy The Code &
Try With Live Editor
Output
#3 Code Example- GCD for both positive and negative numbers
Code -
Java Programming
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);
}
}
Copy The Code &
Try With Live Editor
Output
Demonstration
Java Programing Example to Find GCD of two Numbers-DevsEnv