LCM of 2 Numbers

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 37:- LCM of 2 Numbers

To calculate the Least Common Multiple (LCM) of two numbers in Java, you can use the formula:

LCM(a, b) = (|a * b|) / GCD(a, b)

where GCD(a, b) represents the Greatest Common Divisor of the two numbers a and b. Since we have already discussed how to calculate GCD in the previous answer, you can use the same calculateGCD method from the previous example. Here's a Java program to calculate the LCM of two given numbers:

javaCopy code

import java.util.Scanner; public class LCDCalculator {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.print("Enter the first number: ");        int num1 = scanner.nextInt();        System.out.print("Enter the second number: ");        int num2 = scanner.nextInt();        // Calculate the LCM using the formula LCM(a, b) = (|a * b|) / GCD(a, b)        int lcm = calculateLCM(num1, num2);        System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);        scanner.close();    }    // Function to calculate LCM using GCD    public static int calculateLCM(int a, int b) {        int gcd = calculateGCD(a, b);        return Math.abs(a * b) / gcd;    }    // Function to calculate GCD using the Euclidean algorithm    public static int calculateGCD(int a, int b) {        while (b != 0) {            int temp = b;            b = a % b;            a = temp;        }        return a;    } }

Example output:

mathematicaCopy code

Enter the first number: 12 Enter the second number: 18 LCM of 12 and 18 is: 36

In the program above, we take the user input for the two numbers and store them in num1 and num2 variables. We then call the calculateLCM function to calculate the LCM using the GCD method we defined earlier. The calculateLCM function uses the formula to compute the LCM and returns the result.

The program then prints the LCM of the two numbers to the console.

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?