Welcome to another exciting lesson on Data Structures and Algorithms at CodeYourCraft! Today, we're going to learn about two fundamental mathematical concepts: Greatest Common Divisor (GCD) and Least Common Multiple (LCM). These concepts are essential in various programming problems and real-world applications. Let's dive right in! š
The Greatest Common Divisor (GCD) of two integers is the largest positive integer that can divide both numbers without leaving a remainder. In simpler terms, it's the largest number that both numbers share as a factor.
Let's find the GCD of 48 and 18:
The Least Common Multiple (LCM) of two integers is the smallest positive integer that is a multiple of both numbers. In simpler terms, it's the smallest number that both numbers can divide evenly into.
Let's find the LCM of 48 and 18:
The Euclidean algorithm is a method to find the GCD and LCM of two numbers efficiently. Let's understand how it works for finding GCD first.
a is greater than b, swap a and b.r be the remainder when a is divided by b.a with b and b with r.r is zero. The last non-zero value of b is the GCD.g.|a*b| / g.What is the GCD of 15 and 30?
Here are code examples in Python and JavaScript demonstrating the Euclidean algorithm for finding GCD and LCM.
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
return abs(a * b) // gcd(a, b)
print("GCD:", gcd(48, 18)) # Output: 18
print("LCM:", lcm(48, 18)) # Output: 108function gcd(a, b) {
while (b) {
[a, b] = [b, a % b];
}
return a;
}
function lcm(a, b) {
return Math.abs(a * b) / gcd(a, b);
}
console.log("GCD:", gcd(48, 18)); // Output: 18
console.log("LCM:", lcm(48, 18)); // Output: 108You've now learned about GCD and LCM, their significance, and how to find them using the Euclidean algorithm. Remember to practice these concepts with various examples to make them second nature. Happy coding! š