Greatest Common Divisor in Javascript

Posted: , Last Updated:

 * Recursive implementation to find the gcd (greatest common divisor) of two integers using the euclidean algorithm.
 * For more than two numbers, e.g. three, you can box it like this: gcd(a,gcd(b,greatest_common_divisor.c)) etc.
 * This runs in O(log(n)) where n is the maximum of a and b.
 * @param a the first integer
 * @param b the second integer
 * @return the greatest common divisor (gcd) of the two integers.
const gcd = function (a, b) {
    if (b === 0) return a;
    return gcd(b, a % b);

module.exports = {gcd}

About the algorithm and language used in this code snippet:

Euclidean Greatest Common Divisor (GCD) Algorithm

The greatest common divisor of two numbers (in this case a and b) is the biggest number which both numbers can be divided by without a rest. This greatest common divisor algorithm, called the euclidean algorithm, determines this number. The greatest common divisor is also often abbreviated as gcd.

Description of the Algorithm

The basic principle behind thus gcd algorithm is to recursively determine the gcd of a and b by determining the gcd of b and a % b This hinges on the fact that the gcd of two numbers also divides their difference, e.g. the greatest common divisor of 16 and 24 (which is 8) is also the greatest common divisor of 24-16=8. This is therefore also true for 16 and 40 - in fact, rather than taking the difference, the remainder can also be used (repeatedly recursing on the difference will inevitable “pass” the remainder). In summary, the euclidean gcd algorithm uses these 2 steps:

  1. if a or b is 0, return the other one.
  2. Repeat with the new a as b and the new b as a % b.

Using the remainder has a much faster runtime compared to using the difference.

Example of the Algorithm

When computing the gcd of 1071 and 462, the following steps will be taken:

  1. a is 1071, new b is 462
  2. Recursing with new a = b and new b = a % b…
  3. New a is 462, new b is 147
  4. Recursing with new a = b and new b = a % b…
  5. New a is 147, new b is 21
  6. Recursing with new a = b and new b = a % b…
  7. New a is 21, new b is 0
  8. b is 0, stopping recursion, a is the gcd: 21

Runtime Complexity of the Algorithm

The runtime complexity of the Euclidean greatest common divisor algorithm is O(log(max(a,b))) (the logarithm of the maximum of the two numbers). Using the remainder rather than the difference is considerably faster - if the difference would’ve been used this greatest common divisor algorithm would’ve had a runtime of O(max(a,b))

Space Complexity of the Algorithm

The space complexity of the Euclidean greatest common divisor algorithm is equal to the runtime, since every recursive call is saved in the stack and everything else is constant.


JavaScript is an interpreted scripting language previously primarily used in web pages (executed in browsers) that has since found popularity for back-end and other tasks as well through node.js

While it borrows a lot of its syntax from Java, it is a very different language and should not be confused.

Getting to “Hello World” in JavaScript

The most important things first - here’s how you can run your first line of code in JavaScript. If you want to use JavaScript for backend, follow the chapter on how to print Hello World using Node.js. If you want to use JavaScript in the frontend (i.e. in web pages), follow the chapter on how print Hello World in the browser.

Getting to “Hello World” in JavaScript using the browser

  1. Create a file named hello_world.html
  2. Open it using a text editor (e.g. Sublime Text, or just the default Windows editor)
  3. Paste the following code snippet:

    <script type="application/javascript">
        // This prints to the browsers console
        console.log("Hello World")
        // This opens a popup
        alert("Hello world")
    (Website content)
  4. Open this file using your browser (by typing the location into the address bar)
  5. You should see a pop-up saying “Hello World”
  6. If you use your browsers console (e.g. in Chrome: right-click -> inspect), you will see it printed there as well.

The reason we’re wrapping the script in HTML is that the browser will otherwise not execute the JavaScript, but just show it’s contents.

Getting to “Hello World” in JavaScript using Node.js

  1. Download and install the latest version of Node.js from You can also download an earlier version if your use case requires it.
  2. Open a terminal, make sure the node command is working. If you’re getting a “command not found” error (or similar), try restarting your command line, and, if that doesn’t help, your computer. If the issue persists, here are some helpful StackOverflow questions for each platform:

  3. As soon as that’s working, copy the following snippet into a file named hello_world.js:

    console.log("Hello World");
  4. Change directory by typing cd path/to/hello_world, then run node hello_world.js. This should print “Hello World” to your Terminal.

That’s it! Notice that the entry barrier is similarly low as it is for Python and many other scripting languages.

Fundamentals in JavaScript

To understand algorithms and technologies implemented in JavaScript, one first needs to understand what basic programming concepts look like in this particular language. Each of the following snippets can be executed using Node.js on its own, as no boilerplate is required. In the browser, the code needs to be surrounded by HTML just like the Hello World example for the browser shown above.

Variables and Arithmetic

Variables in JavaScript are dynamically typed, meaning the content of a variable is determined at runtime and does not need to be specified when writing the code.

var number = 5;
var decimalNumber = 3.25;
var result = number * decimalNumber;
var callout = "The number is ";
// In this instance, the values are concatenated rather than added because one of them is a String.
console.log(callout + result);

This will print ‘The number is 16.25’.


Arrays in JavaScript are implemented as objects, with the index just being the name of the property. This makes them dynamically sized. The whole concepts of objects and arrays are merged in JavaScript, as demonstrated by the following snippet.

var integers = {}; // initialized as object
integers[3] = 42; // assigned using array index
console.log(integers["3"]); // Accessed using property name, prints "42"

var strings = ["Hello"]; // strings[0] is now Hi
strings[2] = "World"; // index 1 skipped
strings.beautiful = "Beautiful" // Assigned using property name

console.log(strings[0] + " " + strings["beautiful"] + " " + strings[2]); // Prints "Hello World"


Just like most programming languages, JavaScript can do if-else statements. Additionally, JavaScript can also do switch-case statements.

var value = 5;
if(value === 5){
    console.log("Value is 5");
} else if(value < 5){
    console.log("Value is less than 5");
} else {
    console.log("Value is something else");

switch (value){
    case 1:
        console.log("Value is 1");
        break; // Don't go further down the cases
    case 2:
        console.log("Value is 2");
        break; // Don't go further down the cases
    case 3:
        console.log("Value is 3");
        break; // Don't go further down the cases
    case 4:
        console.log("Value is 4");
        break; // Don't go further down the cases
    case 5:
        console.log("Value is 5");
        break; // Don't go further down the cases
        console.log("Value is something else");

The above JavaScript code will print “Value is 5” twice.


JavaScript supports for, while as well as do while loops. break and continue statements are also supported. The below example illustrates the differences:

var value = 2;
for (var i = 0; i < value; i++) {
while (value > 0) {
do {
} while (value > 0);

This will print the following to the terminal:


Note the last 0: it is printed because in the do-while-loop, compared to the while-loop. the code block is executed at least once before the condition is checked.


Functions in JavaScript can be declared using many different syntaxes, for example as object properties, as variables, or, in more recent JavaScript versions, as part of a class.

Here’s an example of a JavaScript function as a variable:

var my_function = function(){
    console.log("Hello World")


Here’s an example of a JavaScript function as an object property:

var function_object = {}
function_object.my_function = function(){
    console.log("Hello World")


And here’s an example of calling a function of an object of a class:

class FunctionClass {
        console.log("Hello World")

new FunctionClass().my_function();

(all of these examples print “Hello World”.)


As previously mentioned, JavaScript shares much of its Syntax with Java. JavaScript requires the use of curly brackets ({}) to surround code blocks in conditions, loops, functions etc.; It doesn’t always require semicolons at the end of statements, but their use is encouraged, as their usage means the use of whitespace for preferred formatting (e.g. indentation of code pieces) does not affect the code.

Advanced Knowledge of JavaScript

JavaScript was first released in 1993 and is multi-paradigm. It is primarily event-driven and functional, but also follows object-oriented and imperative paradigms. It’s dynamically typed, but offers some amount of static typing in recent versions and dialects such as TypeScript. For more information, JavaScript has a great Wikipedia) article.