LCM in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

/* C - LCM of two integers (input: 12 18) */
#include <stdio.h>
#include <stdlib.h>

long long gcd(long long a, long long b){
    a = llabs(a); b = llabs(b);
    while (b) { long long t = a % b; a = b; b = t; }
    return a;
}

int main() {
    long long a, b;
    if (scanf("%lld %lld", &a, &b) != 2) return 0;
    if (a == 0 || b == 0) { printf("LCM is 0\n"); return 0; }
    long long g = gcd(a,b);
    long long l = llabs(a / g * b);
    printf("LCM of %lld and %lld is %lld\n", a, b, l);
    return 0;
}

C Output

Input:
12 18

Output:
LCM of 12 and 18 is 36



C++ Program

// C++ - LCM of two integers (input: 8 20)
#include <iostream>
#include <cstdlib>
using namespace std;
long long gcd(long long a, long long b){
    a = llabs(a); b = llabs(b);
    while (b) { long long t = a % b; a = b; b = t; }
    return a;
}
int main(){
    long long a,b; if(!(cin>>a>>b)) return 0;
    if(a==0 || b==0){ cout<<"LCM is 0\n"; return 0; }
    long long g = gcd(a,b);
    long long l = llabs(a / g * b);
    cout<<"LCM of "<<a<<" and "<<b<<" is "<<l<<"\n";
    return 0;
}

C++ Output

Input:
8 20

Output:
LCM of 8 and 20 is 40



JAVA Program

// Java - LCM of two integers (input: 7 3)
import java.util.*;
public class Main {
    static long gcd(long a, long b){
        a = Math.abs(a); b = Math.abs(b);
        while (b != 0) {
            long t = a % b; a = b; b = t;
        }
        return a;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        if(!sc.hasNextLong()) return;
        long a = sc.nextLong(), b = sc.nextLong();
        if (a == 0 || b == 0) { System.out.println("LCM is 0"); return; }
        long g = gcd(a,b);
        long l = Math.abs(a / g * b);
        System.out.println("LCM of " + a + " and " + b + " is " + l);
    }
}

JAVA Output

Input:
7 3

Output:
LCM of 7 and 3 is 21



Python Program

# Python - LCM of two integers (input: 21 6)
import sys
data = sys.stdin.read().strip().split()
if len(data) < 2: 
    sys.exit()
a, b = int(data[0]), int(data[1])
def gcd(x,y):
    x, y = abs(x), abs(y)
    while y:
        x, y = y, x % y
    return x
if a == 0 or b == 0:
    print("LCM is 0")
else:
    g = gcd(a,b)
    l = abs(a // g * b)
    print(f"LCM of {a} and {b} is {l}")

Python Output

Input:
21 6

Output:
LCM of 21 and 6 is 42



In-Depth Learning – Entire Concept in Paragraphs
Example: 
Least Common Multiple (LCM) of two integers is the smallest positive integer that both numbers divide. One common and effective method of calculating it is to utilize the greatest common divisor (GCD). First calculate GCD(a, b) using Euclid's algorithm by repeatedly replacing the pair (a, b) with (b, a mod b) until b is zero; the remaining a is the GCD. Then LCM can be computed from the identity lcm(a, b) = |a / gcd(a,b) * b| which is less likely to overflow than simple |a*b|/gcd since the division occurs prior to multiplication. The code in both languages adheres to this blueprint: read two integers, treat the zero explicitly because LCM with zero is traditionally zero in most programming assignments, calculate gcd with abs to accommodate negative inputs, then calculate and output the LCM. Using long long (or Python int) makes the code safe for fairly large integers.

Real-Life Analogy: 
Suppose we have two traffic lights that light up every A seconds and every B seconds separately. The LCM is the first time (after time zero) when both lights light at the same time again. Applying the GCD-first approach is like first determining the largest rhythm they have in common — the largest step you can take with both — then stretching to the smallest time when those steps coincide. This makes the concept intuitive: determine the common beat (GCD) and add that to the sizes to obtain the first concurrent beat (LCM).

Why It Matters: 
Becoming able to calculate LCM quickly illustrates two key programming concepts. First, Euclid's algorithm for GCD is a typical example of an algorithm that is straightforward and very speedy — it takes logarithmic time compared to the number sizes. Second, the algebraic identity relating gcd and lcm illustrates a strong pattern where one calculated property reduces the calculation of the other and demonstrates mindful ordering of operations to prevent overflow. These are skills that transfer: algorithmic thinking to minimize a problem, numerical safety concerns, and applying mathematical identities to make computations faster.

Learning Insights: 
Using LCM provides experience in integer arithmetic, edge-case consideration, and code portability between languages. The necessity of taking absolute values demonstrates input normalization, and the direct check for zero shows defensive programming. The decision to calculate a/gcd prior to multiplying by b is an intentional micro-optimization to maintain smaller intermediate values and prevent overflow for languages with fixed-width integers. Students also become proficient in writing and testing tiny utility functions such as gcd and in employing standard I/O idioms for C, C++, Java and Python.

Interview and Real-World Applications: 
Interviewers often ask GCD/LCM questions since they are easy to name but let you demonstrate knowledge of algorithms, number theory fundamentals, and code readability. In real projects, LCM shows up when coordinating periodic operations, scheduling recurring tasks, computing step sizes for discrete simulations, and implementing systems where several timers or cycles need coordination. Describing why you divide by the gcd before multiplication and what you do with negative or zero inputs typically earns points in interviews because it indicates attention to detail and numerical accuracy.

Practical Details and Edge Cases: 
If an input is zero, most problem statements anticipate the LCM to be zero and the sample implementations here do that as well. Mathematically, LCM(0,0) is often said to be undefined, so it's interesting to define behavior for such edge cases in practical work. Also, when working with very large integers beyond 64-bit ranges, utilize big-integer libraries (Java BigInteger, Python int already arbitrary precision) and rewrite the formula to prevent intermediate overflow.

SEO-friendly explanation paragraph: 
This LCM tutorial demonstrates tidy, functioning implementations in C, C++, Java, and Python and discusses why calculating the GCD first using Euclid's algorithm results in a efficient and secure way of computing the least common multiple. The code snippet illustrates typical input/output behavior and defensive zero and negative value handling, and the technique using lcm = |a / gcd(a,b) * b| does not overflow but is fast even for large values. Novices looking for "LCM program C C++ Java Python", "how to calculate LCM by GCD", or "least common multiple example code" will appreciate these brief, accurate examples and the step-by-step conceptual explanation to learn, interview preparation, and real-world scheduling or synchronization issues.