For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Finding the greatest common divisor (GCD) of two numbers in Java Programming is a fundamental operation in computer science and mathematics. The GCD is the largest positive integer that divides two or more numbers without a remainder.Understanding how to find GCD of two numbers in Java provides a strong foundation for solving complex programming problems in cryptography, fraction simplification, and algorithmic optimization.
Build a strong foundation in Java and beyond. Join the Software Engineering course by upGrad to accelerate your tech journey.What is GCD and Why It Matters
The GCD (also called the Greatest Common Factor or GCF) represents the largest positive integer that divides two numbers completely. For example, the GCD of 36 and 48 is 12, as 12 is the largest number that divides both 36 and 48 without leaving a remainder.
Already working with Java? Now lead innovation with Generative AI—explore the Executive Programme for Business Leaders by IIIT-B and upGrad.
The Euclidean algorithm is the most efficient way to find the GCD of two numbers in Java programming. It uses the principle that if a and b are two positive integers, gcd(a,b) = gcd(b, a % b).
Code:
public class EuclideanGCD {
public static void main(String[] args) {
int number1 = 48;
int number2 = 36;
int gcd = findGCD(number1, number2);
// Display the result
System.out.println("GCD of " + number1 + " and " + number2 + " is: " + gcd);
}
// Method to find GCD using Euclidean algorithm
public static int findGCD(int a, int b) {
// Base case
if (b == 0) {
return a;
}
// Recursive call with (b, a % b)
return findGCD(b, a % b);
}
}
Output:
GCD of 48 and 36 is: 12
This implementation uses recursion to efficiently compute the GCD of two numbers, making it ideal for small to medium-sized inputs.
Java developers are in high demand—especially with cloud and DevOps skills. Gain both with this Professional Certificate Program by upGrad.
For those who prefer an iterative solution or are concerned about stack overflow with recursive methods for large numbers, here's an efficient iterative implementation:
public class IterativeGCD {
public static void main(String[] args) {
int number1 = 105;
int number2 = 30;
int gcd = findGCD(number1, number2);
// Display the result
System.out.println("GCD of " + number1 + " and " + number2 + " is: " + gcd);
}
// Method to find GCD iteratively using Euclidean algorithm
public static int findGCD(int a, int b) {
// Ensure a and b are positive
a = Math.abs(a);
b = Math.abs(b);
// Loop until remainder becomes zero
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
Output:
GCD of 105 and 30 is: 15
This iterative method works well for larger numbers and avoids recursion stack limitations that might occur with very large inputs.
To properly find the GCD of two numbers in Java when dealing with negative inputs, we use the absolute values:
public class NegativeNumbersGCD {
public static void main(String[] args) {
int number1 = -42;
int number2 = 56;
int gcd = findGCD(number1, number2);
// Display the result
System.out.println("GCD of " + number1 + " and " + number2 + " is: " + gcd);
}
// Method to find GCD that handles negative numbers
public static int findGCD(int a, int b) {
// Convert to positive numbers
a = Math.abs(a);
b = Math.abs(b);
if (b == 0) {
return a;
}
return findGCD(b, a % b);
}
}
Output:
GCD of -42 and 56 is: 14
The absolute value conversion ensures that the GCD algorithm works correctly regardless of the input numbers' signs.
When building a calculator application, you often need to reduce fractions to their lowest terms. Here's how to use GCD for this purpose:
public class FractionSimplifier {
public static void main(String[] args) {
// Example: Simplify the fraction 48/180
int numerator = 48;
int denominator = 180;
// Find the GCD
int gcd = findGCD(numerator, denominator);
// Simplify the fraction
int simplifiedNumerator = numerator / gcd;
int simplifiedDenominator = denominator / gcd;
// Display results
System.out.println("Original fraction: " + numerator + "/" + denominator);
System.out.println("Simplified fraction: " + simplifiedNumerator + "/" + simplifiedDenominator);
}
// Euclidean algorithm for GCD
public static int findGCD(int a, int b) {
if (b == 0) {
return a;
}
return findGCD(b, a % b);
}
}
Output:
Original fraction: 48/180
Simplified fraction: 4/15
This example demonstrates how finding the GCD of two numbers in Java helps simplify fractions to their lowest terms, a common requirement in many mathematical applications.
For better understanding of which method to use when finding the GCD of two numbers in Java, here's a comparison table:
Method | Advantages | Best Use Case |
Recursive Euclidean | Clean, elegant code | Small to medium numbers |
Iterative Euclidean | No stack overflow concern | Large numbers |
Built-in Math.gcd() | Simplest implementation | Java 9+ projects |
Brute Force | Easier to understand | Educational purposes only |
Since Java 9, you can use the built-in Math.gcd() method to find the GCD of two numbers:
import java.lang.Math;
public class BuiltInGCD {
public static void main(String[] args) {
int number1 = 54;
int number2 = 24;
// Using Java's built-in Math.gcd() method
int gcd = Math.gcd(number1, number2);
// Display the result
System.out.println("GCD of " + number1 + " and " + number2 + " is: " + gcd);
}
}
Output:
GCD of 54 and 24 is: 6
The built-in method provides a clean and efficient way to find the GCD without implementing the algorithm yourself.
Learning how to find GCD of two numbers in Java opens doors to solving many practical coding problems. The GCD calculation is a building block for fraction work, cryptography algorithms, and even calendar applications. You've now seen several ways to implement GCD in Java - from the classic Euclidean algorithm to Java's built-in Math.gcd() method.
Remember that the recursive approach works well for most situations, but switch to iterative for very large numbers. For modern Java projects, the built-in method is your best choice as it's already optimized. Whichever method you choose, understanding the underlying algorithm will make you a better programmer.
Try implementing these GCD methods in your next Java project. You'll find that this seemingly simple mathematical operation can solve complex problems with surprising elegance and efficiency!
The time complexity of the Euclidean algorithm is O(log(min(a,b))), making it highly efficient even for large numbers. This logarithmic complexity means the algorithm remains fast even when dealing with very large integers, unlike brute force approaches.
Yes, you can find the GCD of multiple numbers by finding the GCD of the first two, then finding the GCD of that result with the third number, and so on. This property makes it possible to extend GCD calculations to any number of integers using the same underlying algorithm.
The Euclidean algorithm reduces the problem size significantly with each step, while brute force checks all possible divisors one by one. Each iteration of the Euclidean algorithm reduces the numbers by a factor proportional to their magnitude, leading to much faster convergence.
In cryptography, GCD helps find coprime numbers (GCD=1) which are essential for generating public and private keys in encryption algorithms. The RSA algorithm particularly relies on GCD calculations to establish secure communications across insecure networks.
No, the GCD of any set of non-zero integers is always a positive integer. The GCD is zero only if all numbers are zero. This is because zero is divisible by every number, creating a special case in GCD calculations.
No, GCD (Greatest Common Divisor) and HCF (Highest Common Factor) refer to the same mathematical concept. The terminology may vary depending on regional mathematical conventions, but they both represent the largest positive integer that divides the given numbers.
For two numbers a and b, their product equals the product of their GCD and LCM: a×b = GCD(a,b) × LCM(a,b). This relationship allows you to calculate the LCM easily once you know the GCD, which is particularly useful in fraction calculations.
Take the absolute values of both numbers before applying the GCD algorithm, as GCD is defined for positive integers. The mathematical definition of GCD applies to the magnitude of the numbers rather than their signs.
Yes, Java 9 and later versions provide Math.gcd() method that calculates the GCD of two integers. This method is implemented natively and is typically faster than user-defined implementations for general use cases.
The iterative approach is generally better for large numbers as it avoids potential stack overflow issues that might occur with recursion. For most practical applications, the iterative method provides better memory efficiency and safety.
The minimum value of GCD for two non-zero integers is 1, which occurs when the numbers are coprime (have no common factors other than 1). Coprime numbers play an important role in number theory and have applications in modular arithmetic.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.