Commit ec9f2b7
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
1 file changed
+13
-18
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | 3 | | |
5 | 4 | | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | | - | |
15 | | - | |
16 | | - | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
17 | 13 | | |
18 | | - | |
19 | | - | |
20 | | - | |
21 | | - | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
22 | 17 | | |
23 | | - | |
| 18 | + | |
0 commit comments