From f280fa631b63e633fcb641c35548c07eaf1bf990 Mon Sep 17 00:00:00 2001 From: David Wu Date: Sat, 16 Dec 2017 20:55:39 +0100 Subject: [PATCH 1/2] Create least-common-multiple-(LCM).md --- snippets/least-common-multiple-(LCM).md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 snippets/least-common-multiple-(LCM).md diff --git a/snippets/least-common-multiple-(LCM).md b/snippets/least-common-multiple-(LCM).md new file mode 100644 index 000000000..1696114f2 --- /dev/null +++ b/snippets/least-common-multiple-(LCM).md @@ -0,0 +1,11 @@ +### Least common multiple (LCM) + +Use this lcm formula `lcm(a,b)=|a*b|/gcd(a,b)` for calculating the least common multiple of two numbers. +Makes use of the [GCD snippet](https://github.com/Chalarangelo/30-seconds-of-code#greatest-common-divisor-gcd). + +```js +const lcm = (x,y) => Math.abs(x*y)/(gcd(x,y)); +const gcd = (x, y) => !y ? x : gcd(y, x % y); +// lcm(10,5) -> 10 +// lcm(12,7) -> 84 +``` From 137fddef9e9a3ceee3e5a739d47f56e0a6d1a91f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 11:26:53 +0200 Subject: [PATCH 2/2] Update least-common-multiple-(LCM).md --- snippets/least-common-multiple-(LCM).md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/snippets/least-common-multiple-(LCM).md b/snippets/least-common-multiple-(LCM).md index 1696114f2..4f3fc2822 100644 --- a/snippets/least-common-multiple-(LCM).md +++ b/snippets/least-common-multiple-(LCM).md @@ -1,11 +1,12 @@ ### Least common multiple (LCM) -Use this lcm formula `lcm(a,b)=|a*b|/gcd(a,b)` for calculating the least common multiple of two numbers. -Makes use of the [GCD snippet](https://github.com/Chalarangelo/30-seconds-of-code#greatest-common-divisor-gcd). +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) => Math.abs(x*y)/(gcd(x,y)); -const gcd = (x, y) => !y ? x : gcd(y, x % y); -// lcm(10,5) -> 10 +const lcm = (x,y) => { + const gcd = (x, y) => !y ? x : gcd(y, x % y); + return Math.abs(x*y)/(gcd(x,y)); +}; // lcm(12,7) -> 84 ```