C program to find lcm of two numbers

C program to find LCM of two numbers

This C program is to find LCM of two numbers.LCM(Least Common Multiple) is the smallest positive number which is divisble by both the numbers.For example lcm of 8 and 12 is 24 as 24 is divisble by both 8(8*3) and 12(12*2).

Logic

We first find the maximum between the two numbers as we will use a for loop to iterate till we reach the maximum value out of both the nos which is divisble by both the numbers.

Dry Run of the Program

Take input ‘a’ ‘b’ .Let us take a=4 and 2.

max=a>b?a:b;   i.e. max=4>2?4:2;  hence max=4

1st iteration for(i=0;i<max;i++) i.e. for(i=0;i<4;i++)

if(max%a==0 && max%b==0)  i.e if(4%4==0 && 4%2==0) as the condition is true we execute the if statements

lcm=max;   i.e  lcm=4;

break; we exit the for loop

Hence print lcm as 4.

Program

#include<stdio.h>
void main()
{
	int a,b,i,max,lcm;
 
  	printf("Enter the two numbers\n");
	scanf("%d%d",&a,&b);
    
    max=a>b?a:b;
    for(i=0;i<max;i++)
    {
        if(max%a==0 && max%b==0)
        {
            lcm=max;
            break;
        }
        max++;
    }
    
    printf("\nLCM of the two numbers = %d",lcm);
 }

Output

Share Me!