Least Common Multiple (LCM) of two numbers is the smallest positive integer which is also a multiple of both the numbers. If any of the two numbers is 0, LCM of those two numbers will be 0. You can find more about LCM of two numbers on Wikipedia.
Algorithm:
- Let
aandbbe the two numbers whose LCM you want to find. - Let
tempbe any temporary number, initially set to the bigger number among a and b. - Check whether
tempis perfectly divisible by bothaandbor not. - If it is, then
tempis the LCM ofaandb, otherwise move to step 5. - Increment the value of
tempand move to step 3.
Instructions:
- Use only the following header file in C program.
#include <stdio.h> - In
main, ask the user to input two numbers whose LCM he/she wants to find.
int a,b, temp; printf("Enter two numbers whose LCM you want to find : "); scanf("%d%d", &a, &b); - Find the LCM of these two numbers
aandbusing the user defined functionfindLCMwhich will return LCM of these two number and print its value.
temp = findLCM(a, b); printf("LCM of %d and %d is %d", a, b, temp); - In
findLCMfunction, define a temporary variablelcmand assign it value of the bigger number amongaandb(i.e. if a > b then lcm = a, otherwise lcm = b). No using a while loop which will run untilllcmbecomes perfectly divisible by bothaandb, and increment the value oflcmin this loop. And finally return the value of variablelcm.
int findLCM(int a, int b) { int lcm = a > b ? a : b; while(lcm % a != 0 || lcm % b != 0) { lcm++; } return lcm; }
Here are some screenshots of sample programs.
You can download the sample code from here.
Incoming search terms:
- code to find lcm of two numbers (1)
- program LCM in C (1)
