Menu
Coddy logo textTech

21. Calculate GCD

Lesson 22 of 31 in Coddy's 30 Days of Logic Building in Javascript course.

The Greatest Common Divisor (GCD) of two numbers is the largest positive integer that divides both numbers without leaving a remainder.

For example, let's find the GCD of 12 and 18:

  1. List the factors of 12: 1, 2, 3, 4, 6, 12.
  2. List the factors of 18: 1, 2, 3, 6, 9, 18.
  3. Identify the largest common factor: In this case, it's 6.

So, GCD(12, 18) = 6. This means 6 is the greatest number that can evenly divide both 12 and 18.

challenge icon

Challenge

Medium

Write a function to calculate the GCD of two numbers.

  • Input: <strong>12</strong>, <strong>18</strong>
  • Output: <strong>6</strong>

Try it yourself

function gcd(a, b) {
    // write your code below
    
}

All lessons in 30 Days of Logic Building in Javascript