Skip to content

Instantly share code, notes, and snippets.

@brittanydionigi
Created July 19, 2017 14:51
Show Gist options
  • Save brittanydionigi/8a47b42348445fc25d266808cb95bdf7 to your computer and use it in GitHub Desktop.
Save brittanydionigi/8a47b42348445fc25d266808cb95bdf7 to your computer and use it in GitHub Desktop.
Greatest Common Denominator

Prompt

Using recursion, find the greatest common denominator of two positive integers.

For example,

greatestCommonDenominator(9, 12) #=> 3

Answer

const gcd = (a, b) => {

  // b will return falsey when it equals 0
  // at this point, we know there is no remainder
  // and we can simply return `a` as the GCD
  if (!b) {
    return a;
  }

  // otherwise, call gcd again with `b` in `a`s spot,
  // and use the remainder of `a % b` as `b`.
  return gcd(b, a % b);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment