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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
12 18
Sample output
LCM = 36
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
LCM = 36
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Find the GCD with Euclid's algorithm and apply LCM(a,b)=|a|/GCD×|b|.
- 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.
