Skip to content

Commit 33921a5

Browse files
Upgrade gcd function: remove recursion
1 parent 99b8adc commit 33921a5

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

src/games/gcd.js

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,14 @@ import {
55
} from '../index.js';
66

77
const gcd = (a, b) => {
8-
if (a > b) {
9-
if (b === 0) {
10-
return a;
11-
} return gcd(b, a % b);
12-
}
13-
if (b > a) {
14-
if (a === 0) {
15-
return b;
16-
} return gcd(a, b % a);
17-
} return a;
8+
if (a === b) {
9+
return a;
10+
} const maxDivisor = a > b ? b : a;
11+
for (let divisor = maxDivisor; divisor > 1; divisor -= 1) {
12+
if (a % divisor === 0 && b % divisor === 0) {
13+
return divisor;
14+
}
15+
} return 1;
1816
};
1917

2018
export default () => {

0 commit comments

Comments
 (0)