update lcm and gcd

This commit is contained in:
Rohit Tanwar
2017-12-29 16:34:06 +05:30
parent 5c6842aae4
commit ed2983abcd
4 changed files with 15 additions and 43 deletions

View File

@ -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
```

View File

@ -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
```

View File

@ -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 gcm = (...arr) => {
arr = [].concat(...arr)
const helperGcd = (x, y) => (!y ? x : gcd(y, x % y));
return arr.reduce((a, b) => helperGcd(a, b))
}
```
```js

View File

@ -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 gcd = (x, y) => (!y ? x : gcd(y, x % y));
return Math.abs(x * y) / gcd(x, y);
};
const lcm = (...arr) => {
arr = [].concat(...arr)
const gcd = (x, y) => (!y ? x : gcd(y, 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
```