LeetCode: Find Greatest Common Divisor of Array Solution

Straight forward: min, max then gcd

Approach

Straight forward:

  • find max
  • find min
  • find gcd between max of min

JavaScript has no built-in gcd function, so we have to implement from scratch

1function gcd(a, b) {
2 if (a % b === 0) {
3 return b
4 }
5 return gcd(b, a % b)
6}

Implementation

1var findGCD = function (nums) {
2 function gcd(a, b) {
3 if (a % b === 0) {
4 return b
5 }
6 return gcd(b, a % b)
7 }
8
9 const max = Math.max.apply(null, nums)
10 const min = Math.min.apply(null, nums)
11
12 return gcd(max, min)
13}

Comments

Loading comments...

Tags

leetcode

array

math

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Length of Last Word

Aug 23, 2021

One-line KO

Previous Post

LeetCode: Rotate List

Aug 22, 2021

Should draw for better imagination of how it works

HoningJS

Search Posts