Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Euclidean Algorithm for calculating GCD in JavaScript
In mathematics, Euclid's algorithm is a method for computing the greatest common divisor (GCD) of two numbers, the largest number that divides both of them without leaving a remainder.
The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number.
For example, 21 is the GCD of 252 and 105 (as 252 = 21 × 12 and 105 = 21 × 5), and the same number 21 is also the GCD of 105 and 252 ? 105 = 147.
How It Works
The algorithm repeatedly replaces the larger number with the difference between the two numbers until both become equal. When that occurs, they represent the GCD of the original two numbers.
Using Subtraction Method
The basic approach uses repeated subtraction to find the GCD:
const num1 = 252;
const num2 = 105;
const findGCD = (num1, num2) => {
let a = Math.abs(num1);
let b = Math.abs(num2);
while (a && b && a !== b) {
if (a > b) {
[a, b] = [a - b, b];
} else {
[a, b] = [a, b - a];
}
}
return a || b;
};
console.log(findGCD(num1, num2));
21
Using Modulo Method (More Efficient)
A more efficient approach uses the modulo operator instead of subtraction:
const findGCDModulo = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
};
console.log(findGCDModulo(252, 105));
console.log(findGCDModulo(48, 18));
console.log(findGCDModulo(17, 13));
21 6 1
Recursive Implementation
The algorithm can also be implemented recursively:
const findGCDRecursive = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
if (b === 0) {
return a;
}
return findGCDRecursive(b, a % b);
};
console.log(findGCDRecursive(252, 105));
console.log(findGCDRecursive(1071, 462));
21 21
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Subtraction | O(max(a,b)) | O(1) | Learning purposes |
| Modulo (Iterative) | O(log(min(a,b))) | O(1) | Production use |
| Modulo (Recursive) | O(log(min(a,b))) | O(log(min(a,b))) | Functional programming |
Common Use Cases
// Simplifying fractions
const simplifyFraction = (numerator, denominator) => {
const gcd = findGCDModulo(numerator, denominator);
return [numerator / gcd, denominator / gcd];
};
console.log(simplifyFraction(252, 105)); // [12, 5]
// Finding LCM using GCD
const findLCM = (a, b) => {
return Math.abs(a * b) / findGCDModulo(a, b);
};
console.log(findLCM(252, 105)); // 1260
[ 12, 5 ] 1260
Conclusion
The Euclidean algorithm efficiently computes the GCD of two numbers. The modulo-based approach is preferred for its O(log n) time complexity, making it suitable for large numbers and production applications.
