Skip to content

Commit ec9f2b7

Browse files
committed
feat: Add GCDandHCF class with Euclidean algorithm implementation
WHAT the code does: - Defines `GCDandHCF` class with a static method `gcd(int m, int n)`. - Uses the **Euclidean algorithm** (via modulus) to compute the Greatest Common Divisor (GCD). - `main()` demonstrates the method with inputs `35` and `56`. WHY this matters: - GCD (also known as HCF: Highest Common Factor) is a fundamental concept in number theory. - The Euclidean algorithm is one of the most efficient methods to compute GCD. - Understanding GCD is useful in simplifying fractions, cryptography, and algorithm design. HOW it works: 1. Start with `(m, n) = (35, 56)`. 2. Repeat until `n == 0`: - Store `n` in `temp`. - Update `n = m % n`. - Update `m = temp`. 3. When `n` becomes `0`, `m` holds the GCD. 4. Output: `"GCD of 35 and 56 is: 7"`. Tips & gotchas: - Works for positive integers; behavior undefined for negative inputs without adjustments. - If one number is `0`, the GCD is the other number. - Recursive implementation is shorter but iterative avoids stack overhead. - For Least Common Multiple (LCM), formula is `LCM(a, b) = (a * b) / GCD(a, b)`. Use-cases: - Simplifying fractions and ratios. - Algorithms involving modular arithmetic (e.g., RSA encryption). - Competitive programming and interview problems. - Foundation for extended Euclidean algorithm (used in modular inverses). Short key: algo-gcd-euclidean-modulus. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent c5f9e54 commit ec9f2b7

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed
Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,18 @@
1-
/*
2-
The Greatest Common Divisor (GCD) is also known as the Highest Common Factor (HCF)12345.
1+
/* The Greatest Common Divisor (GCD) is also known as the Highest Common Factor (HCF).
32
It is the largest positive integer that divides two or more numbers without leaving a remainder.
43
*/
54

6-
public class GCDandHCF
7-
{
8-
9-
static int gcd(int m, int n)
10-
{
11-
while(m!=n)
12-
{
13-
if(m>n)m=m-n;
14-
else n=n-m;
15-
}
16-
return m;
5+
public class GCDandHCF {
6+
// Method to calculate GCD using modulus (faster Euclidean algorithm).
7+
static int gcd(int m, int n) {
8+
while (n != 0) {
9+
int temp = n;
10+
n = m % n;
11+
m = temp;
12+
} return m;
1713
}
18-
public static void main(String[] args)
19-
{
20-
21-
System.out.println(gcd(35,56));
14+
public static void main(String[] args) {
15+
int a = 35, b = 56;
16+
System.out.println("GCD of " + a + " and " + b + " is: " + gcd(a, b));
2217
}
23-
}
18+
}

0 commit comments

Comments
 (0)