C PROGRAMMING PROGRAM • LOOPS & NUMBER PROBLEMS

Find the LCM of Two Numbers

Learn how to find the lcm of two numbers using a clear C program.

IntermediateGCDLCMEuclid's algorithm

PROBLEM UNDERSTANDING

Input and expected output

Sample input
12 18
Sample output
LCM = 36

COMPLETE C PROGRAM

Complete C implementation

lcm-of-two-numbers.c
Open in compiler
#include <stdio.h>

int main(void)
{
    long long first, second, a, b;

    printf("Enter two positive integers: ");
    scanf("%lld %lld", &first, &second);
    if (first == 0 || second == 0) {
        printf("LCM = 0\n");
        return 0;
    }
    a = first < 0 ? -first : first;
    b = second < 0 ? -second : second;
    while (b != 0) {
        long long remainder = a % b;
        a = b;
        b = remainder;
    }
    printf("LCM = %lld\n", (first < 0 ? -first : first) / a * (second < 0 ? -second : second));
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

LCM = 36
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Find the GCD with Euclid's algorithm and apply LCM(a,b)=|a|/GCD×|b|.
  3. Display the computed result.

Find the GCD with Euclid's algorithm and apply LCM(a,b)=|a|/GCD×|b|.

EFFICIENCY

Time and space complexity

Time complexity

O(log min(a,b))

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.