Program to find the LCM of any two numbers.

Here, we have a basic program example to calculate the LCM of two numbers using different languages. The least common multiple (LCM) of two numbers is the lowest possible number that can be divisible by both numbers. This program is created in c language, c++, Java, and Python.

Code to calculate LCM in C language

#include <stdio.h>
int main() {
    int n1, n2, max;
    printf("\n\n  LCM of two numbers:\n ");
    printf("----------------------\n");
    printf("Enter first positive integers: ");
    scanf("%d", &n1);
    printf("Enter second positive integers: ");
    scanf("%d", &n2);
    max = (n1 > n2) ? n1 : n2;
    while (1) {
        if ((max % n1 == 0) && (max % n2 == 0)) {
            printf("The LCM of %d and %d is %d.", n1, n2, max);
            break;
        }
        ++max;
    }
    return 0;
}

Code to calculate LCM in C++ language

#include <iostream>
using namespace std;

int main()
{
    int n1, n2, max;
    cout<<"\n\n  LCM of two numbers:\n ";
    cout<<"----------------------\n";
    cout << "Enter first number: ";
    cin >> n1;
    cout << "Enter second number: ";
    cin >> n2;
    max = (n1 > n2) ? n1 : n2;
    do
    {
        if (max % n1 == 0 && max % n2 == 0)
        {
            cout << "LCM = " << max;
            break;
        }
        else
            ++max;
    } while (true);

    return 0;
}

Code to calculate LCM in Python language

hcf=1
print("\n\n  LCM of two numbers:\n ");
print("----------------------\n");
n1 = int(input("Input 1st number for LCM: "))
n2 = int(input("Input 2nd number for LCM: "))
if n1 > n2:
    greater = n1
else:
    greater = n2
while(True):
    if((greater % n1 == 0) and (greater % n2 == 0)):
        lcm = greater
        break
    greater += 1

print("\nLCM of ",n1," and ",n2," is: ",lcm)

Code to calculate LCM in Java language

import java.util.*;
public class lcm {
    public static void main(String[] args) {     
         int n1, n2, max;
        System.out.println("\n\n  LCM of two numbers:\n ");
        System.out.println("----------------------\n");
       
        Scanner s=new Scanner(System.in);
	System.out.println("Input 1st number for HCF: ");
        n1= s.nextInt();
        System.out.println("Input 2nd number for HCF: ");
        n2= s.nextInt();

       max = (n1 > n2) ? n1 : n2;
        while(true) {
        if ((max % n1 == 0) && (max % n2 == 0)) {
           System.out.println("The LCM of "+n1+" and "+n2+ " is: "+max);
            break;
        }
        ++max;
        }
      }
}