Skip to content

Commit eef66c9

Browse files
committed
fix & optimize gcd function
- handle gcd of negative numbers - fix the case when one of the numbers is equal to zero, gcd(0, x) = absolute value of x - optimize using modulo instead of repeated subtractions
1 parent 7d33c7c commit eef66c9

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/ts/algorithms/math/gcd.ts

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
export const gcd = (num1: number, num2: number): number => {
2-
if (num1 === 0 || num2 === 0) {
3-
return 0;
2+
if (num1 < 0 || num2 < 0) {
3+
return gcd(Math.abs(num1), Math.abs(num2));
44
}
5-
if (num1 === num2) {
5+
if (num1 === 0) {
6+
return num2;
7+
}
8+
if (num2 === 0) {
69
return num1;
710
}
811
if (num1 > num2) {
9-
return gcd(num1 - num2, num2);
12+
return gcd(num1 % num2, num2);
1013
}
11-
return gcd(num1, num2 - num1);
14+
return gcd(num1, num2 % num1);
1215
};
1316

1417
export const gcdArray = (num: number[]) => {

0 commit comments

Comments
 (0)