Merge pull request #385 from kriadmin/master
[FIX #295] Update lcm.md and gcd.md
This commit is contained in:
@ -1,17 +0,0 @@
|
||||
### arrayGcd
|
||||
|
||||
Calculates the greatest common denominator (gcd) of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the greatest common denominator of an array of numbers.
|
||||
|
||||
```js
|
||||
const arrayGcd = arr => {
|
||||
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||
return arr.reduce((a, b) => gcd(a, b));
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
arrayGcd([1, 2, 3, 4, 5]); // 1
|
||||
arrayGcd([4, 8, 12]); // 4
|
||||
```
|
||||
@ -1,18 +0,0 @@
|
||||
### arrayLcm
|
||||
|
||||
Calculates the lowest common multiple (lcm) of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
|
||||
|
||||
```js
|
||||
const arrayLcm = arr => {
|
||||
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||
const lcm = (x, y) => x * y / gcd(x, y);
|
||||
return arr.reduce((a, b) => lcm(a, b));
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
arrayLcm([1, 2, 3, 4, 5]); // 60
|
||||
arrayLcm([4, 8, 12]); // 24
|
||||
```
|
||||
@ -1,13 +1,17 @@
|
||||
### gcd
|
||||
|
||||
Calculates the greatest common divisor between two numbers.
|
||||
Calculates the greatest common divisor between two or more numbers/arrays.
|
||||
|
||||
Use recursion.
|
||||
The `helperGcd `function uses recursion.
|
||||
Base case is when `y` equals `0`. In this case, return `x`.
|
||||
Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||
|
||||
```js
|
||||
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||
const gcd = (...arr) => {
|
||||
let data = [].concat(...arr);
|
||||
const helperGcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||
return data.reduce((a, b) => helperGcd(a, b));
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -1,17 +1,20 @@
|
||||
### lcm
|
||||
|
||||
Returns the least common multiple of two numbers.
|
||||
Returns the least common multiple of two or numbers/arrays.
|
||||
|
||||
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
|
||||
The GCD formula uses recursion.
|
||||
|
||||
```js
|
||||
const lcm = (x, y) => {
|
||||
const lcm = (...arr) => {
|
||||
let data = [].concat(...arr);
|
||||
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||
return Math.abs(x * y) / gcd(x, y);
|
||||
};
|
||||
const helperLcm = (x, y) => x * y / gcd(x, y);
|
||||
return arr.reduce((a, b) => helperLcm(a, b))
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
lcm(12, 7); // 84
|
||||
lcm([1,3,4],5); // 60
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user