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:
- List the factors of 12: 1, 2, 3, 4, 6, 12.
- List the factors of 18: 1, 2, 3, 6, 9, 18.
- 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
MediumWrite 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
1Introduction
What is here for you?