Update and rename gcdOfArray.md to arrayGcd.md
Updated description and naming for consistency.
This commit is contained in:
14
snippets/arrayGcd.md
Normal file
14
snippets/arrayGcd.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
### 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));
|
||||||
|
}
|
||||||
|
// arrayGcd([1,2,3,4,5]) -> 1
|
||||||
|
// arrayGcd([4,8,12]) -> 4
|
||||||
|
```
|
||||||
@ -1,13 +0,0 @@
|
|||||||
|
|
||||||
### gcdOfArray
|
|
||||||
|
|
||||||
It finds the GCD of all the numbers in an array by using `Array.reduce()` and the fact that `gcd(a,b,c) = gcd(gcd(a,b),c)`
|
|
||||||
|
|
||||||
```js
|
|
||||||
const gcdOfArray = arr =>{
|
|
||||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
|
||||||
return arr.reduce((a,b) => gcd(a,b))
|
|
||||||
}
|
|
||||||
// gcdOfArray([1,2,3,4,5]) -> 1
|
|
||||||
// gcdOfArray([4,8,12]) -> 4
|
|
||||||
```
|
|
||||||
Reference in New Issue
Block a user