Mathematical algorithms are also a very important topic for programming interviews. In this article, you’ll learn how to find GCD and LCM of two numbers using C++, Python, C, and JavaScript.
How to Find the GCD of Two Numbers
The greatest common divisor (GCD) or highest common factor (HCF) of two numbers is the largest positive integer that perfectly divides the two given numbers. You can find the GCD of two numbers using the Euclidean algorithm.
In the Euclidean algorithm, the greater number is divided by the smaller number, then the smaller number is divided by the remainder of the previous operation. This process is repeated until the remainder is 0.
For example, if you want to find the GCD of 75 and 50, you need to follow these steps:
Divide the greater number by the smaller number and take the remainder.
Divide the smaller number by the remainder of the previous operation.
Now, the remainder becomes 0, thus the GCD of 75 and 50 is 25.
C++ Program to Find the GCD of Two Numbers
Below is the C++ program to find the GCD of two numbers:
Output:
Python Program to Find the GCD of Two Numbers
Below is the Python program to find the GCD of two numbers:
Output:
C Program to Find the GCD of Two Numbers
Below is the C program to find the GCD of two numbers:
Output:
JavaScript Program to Find the GCD of Two Numbers
Below is the JavaScript program to find the GCD of two numbers:
Output:
How to Find the LCM of Two Numbers
The least common multiple (LCM) of two numbers is the smallest positive integer that is perfectly divisible by the two given numbers. You can find the LCM of two numbers using the following mathematical formula:
To find the LCM of two numbers programmatically, you need to use the function to find the GCD of two numbers.
C++ Program to Find the LCM of Two Numbers
Below is the C++ program to find the LCM of two numbers:
Output:
Python Program to Find the LCM of Two Numbers
Below is the Python program to find the LCM of two numbers:
Output:
C Program to Find the LCM of Two Numbers
Below is the C program to find the LCM of two numbers:
Output:
JavaScript Program to Find the LCM of Two Numbers
Below is the JavaScript program to find the LCM of two numbers:
Output:
Learn More About Mathematical Algorithms
Mathematical algorithms play a vital role in programming. It’s wise to know about some of the basic programs based on mathematical algorithms like Sieve Algorithms, Prime Factorization, Divisors, Fibonacci Numbers, nCr Computations, etc.
Currently, functional programming is at the top of programming trends on the internet. The functional programming paradigm treats computing like mathematical functions and this concept is very useful in programming. You must know about functional programming and which programming languages support it to be the most efficient programmer you can be.