LCM of Two Numbers in JavaIn arithmetic, the Least Common Multiple (LCM) of two or more numbers is the least positive number that can be divided by both the numbers, without leaving the remainder. It is also known as Lowest Common Multiple (LCM), Least Common Denominator, and Smallest Common Multiple. It is denoted by LCM (a, b) or lcm (a, b) where a and b are two integers. It is used when we add, subtract, or compare the fractions. While we perform addition or subtraction of the fractions, we find the LCM of the denominators and then solve the fractions. The LCM of the denominators is known as the Least Common Denominator (LCD). Properties of LCM
How to Find LCM?There are four methods to find the LCM, are as follows:
Using the Greatest Common Divisor (GCD) MethodWe can also calculate the LCM by using the GCD. The formula for LCM using the GCD is: Greatest Common Divisor: It is the highest number that completely divides two or more numbers. It is abbreviated for GCD. It is also known as the Greatest Common Factor (GCF) or the Highest Common Factor (HCF). How to Find GCD? In order to find the GCD follow the steps given below:
Let's understand it through examples. Example: Find the LCM of 8 and 10. Solution: According to the formula that we have learned above: First, we find the GCD of 8 and 10. Factors of 8: 1, 2, 4, 8 Factors of 10: 1, 2, 5, 10 Common Factors: 1, 2 Greatest Common Divisor: 2 Hence, the LCM of 8 and 10 is 40. Let's implement the logic in a Java program. Using if Statement LcmExample1.java Output: The LCM of 12 and 9 is 36. Using Recursion LcmExample2.java Output: Enter the first number: 45 Enter the second number: 78 LCM of 45 and 78 is 1170 Using Multiples of NumbersIt is a very lengthy method, so it is not usually used. Follow the steps given below to find the LCM using multiples of numbers.
Let's understand it through examples. Example: What is the LCM of 9 and 12. Solution: Multiples of 9: 9, 18, 27, 36 Multiples of 12: 12, 24, 36 LCM (9,12)=36 because it is a common multiple in both. Hence, the LCM of 9 and 12 is 36. Let's implement the logic in a Java program. LcmExample4.java Output: Enter the first number: 123 Enter the second number: 213 LCM of 123 and 213 is: 8733
Next TopicPerfect Number Program in Java
