How To Find The GCD Of Two Integers In Javascript

[lastupdated]
The gcd of two integers is the largest integer that divides evenly into both integers with no remainder. This article describes how to write the JavaScript code to calculate the gcd of the two integers.

Calculate The GCD OF Two Integers With User Input In The Developer Console

Unfortunately, JavaScript does not have a native function to calculate gcd. But no problem, this article will show you the JavaScript code to calculate GCD.

Below is the JavaScript code:

function gcd(x,y) {
  // if y > x, then switch them
  if (y > x) {
    let temp1 = y;
    y = x;
    x = temp1;
  }

  // edge cases. If x or y are negative, if one or both of them 
  // are a 0, or if they are the same number.
  if (x == 0 && y == 0) return 1;
  if (x == 0) return y;
  if (y == 0) return x;
  if (x < 0) x = -x;
  if (y < 0) y = -y; if (x == y) return x; // Using the Euclidean algorithm with x being the divisor and y being the remainder // for each step after the first step while (y > 0) {
    let temp2 = y;
    y = x % y;
    x = temp2;
  }
  
  // return the divisor when the remainder is 0
  return x;
}

To test this code, all you need to do is to open up a Firefox or Chrome browser and then type ‘F12’. The developer console will show up. Then just paste in the JavaScript function.

You can also just copy and paste that code into a Node.js shell, and invoke the gcd function as you like.

Then you can test out the gcd of various pairs of integers. For example,
gcd(64,784)
should print out 16.

You can also download the code here.

If you prefer to have the JavaScript displayed on the screen with HTML, you could just take the code above, and add an HTML form, and on submission, calculate the gcd of the two integers from two text input boxes where the user enters the integers.

Want to know how to calculate the gcd of two integers in other languages? See how to do it inΒ Python. and how to do it in PHP.

What did you think of this article? Have anything to add? Let’s discuss it in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *