How To Find The GCD Of Two Integers In Javascript

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. And
gcd(100,30)
should print out 10.
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.


πŸš€ Embark on an Epic Time-Travel Adventure with Watson! πŸ•πŸ¦–πŸŽ¨

Take a journey through time with Watson the Time-Travelling Dog: Dogs and Dinosaurs Adventure Coloring Book 1.

Join Watson and his dog brother Sherlock as they meet dinosaurs, make new friends, and embark on an unforgettable adventure! Perfect for kids, dog lovers, and coloring book enthusiasts alike.

Why you'll love it:

  • Engaging, fun-filled story
  • Beautiful illustrations to color
  • Ideal for family fun or a thoughtful gift

Ready for an adventure that sparks creativity and fun? πŸ“– Grab your copy today and let the time-traveling excitement begin!

Get your book now πŸ‘‡

Get your book here!

Leave a Reply

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