2018-10-04 14:37:37 +01:00
|
|
|
---
|
|
|
|
id: 5a23c84252665b21eecc7e82
|
2020-11-27 19:02:05 +01:00
|
|
|
title: Greatest common divisor
|
2018-10-04 14:37:37 +01:00
|
|
|
challengeType: 5
|
2019-08-05 09:17:33 -07:00
|
|
|
forumTopicId: 302277
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: greatest-common-divisor
|
2018-10-04 14:37:37 +01:00
|
|
|
---
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --description--
|
|
|
|
|
2018-10-04 14:37:37 +01:00
|
|
|
Write a function that returns the greatest common divisor of two integers.
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --hints--
|
|
|
|
|
|
|
|
`gcd` should be a function.
|
|
|
|
|
|
|
|
```js
|
|
|
|
assert(typeof gcd == 'function');
|
2018-10-04 14:37:37 +01:00
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`gcd(24,36)` should return a number.
|
2018-10-04 14:37:37 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
assert(typeof gcd(24, 36) == 'number');
|
|
|
|
```
|
2018-10-04 14:37:37 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`gcd(24,36)` should return `12`.
|
2018-10-04 14:37:37 +01:00
|
|
|
|
|
|
|
```js
|
2020-11-27 19:02:05 +01:00
|
|
|
assert.equal(gcd(24, 36), 12);
|
|
|
|
```
|
2020-09-15 09:57:40 -07:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`gcd(30,48)` should return `6`.
|
|
|
|
|
|
|
|
```js
|
|
|
|
assert.equal(gcd(30, 48), 6);
|
|
|
|
```
|
|
|
|
|
|
|
|
`gcd(10,15)` should return `5`.
|
|
|
|
|
|
|
|
```js
|
|
|
|
assert.equal(gcd(10, 15), 5);
|
2018-10-04 14:37:37 +01:00
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`gcd(100,25)` should return `25`.
|
2018-10-04 14:37:37 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
assert.equal(gcd(100, 25), 25);
|
|
|
|
```
|
2018-10-04 14:37:37 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`gcd(13,250)` should return `1`.
|
2018-10-04 14:37:37 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
assert.equal(gcd(13, 250), 1);
|
|
|
|
```
|
2018-10-04 14:37:37 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`gcd(1300,250)` should return `50`.
|
2018-10-04 14:37:37 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
assert.equal(gcd(1300, 250), 50);
|
|
|
|
```
|
|
|
|
|
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
2018-10-04 14:37:37 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
function gcd(a, b) {
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
}
|
2018-10-04 14:37:37 +01:00
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --solutions--
|
|
|
|
|
|
|
|
```js
|
|
|
|
function gcd(a, b) {
|
|
|
|
return b==0 ? Math.abs(a):gcd(b, a % b);
|
|
|
|
}
|
|
|
|
```
|