Write a C Program to Find LCM of two Number

Prince Patel
By -
0

Write a C Program to Find LCM of two Number.

In the world of mathematics, finding the Lowest Common Multiple (LCM) of two numbers is a common and fundamental operation. LCM is the smallest multiple that is divisible by both of the given numbers. In this article, we will learn how to write a simple C program to calculate the LCM of two numbers without using structures or functions.



Understanding LCM

Before diving into the program, let's get a clear understanding of what LCM is and how it works. The LCM of two numbers, say 'a' and 'b', is the smallest positive integer that is divisible by both 'a' and 'b'. In other words, it's the least common multiple of the two numbers. LCM can be calculated using the following formula:
    LCM(a, b) = (a * b) / GCD(a, b)
Here, GCD stands for the Greatest Common Divisor, which can be found using the Euclidean algorithm. However, for our program, we will not use a separate function to calculate the GCD; instead, we'll calculate it directly in the program.

Here's a  C Program to Find LCM of two Number:


    
#include<stdio.h>
#include<conio.h>
void main()
{
  	int num1, num2, max;

  	// Input the two numbers from the user
	printf("Enter first number: ");
  	scanf("%d", &num1);
  	printf("Enter second number: ");
  	scanf("%d", &num2);

  	// Find the maximum of the two numbers
  	max = (num1 > num2) ? num1 : num2;

    // Loop to find LCM
    while (1) 
    {
      	if (max % num1 == 0 && max % num2 == 0) 
      	{
        	printf("LCM of %d and %d is %d\n", num1, num2, max);
          	break;
      	}
    	max++;
    }
}

Code Explanation
  • We declare three integer variables: num1, num2, and max. num1 and num2 will store the two numbers whose LCM we want to find, and max will be used to iterate through possible multiples until we find the LCM.
  • We use printf and scanf functions to take input from the user for num1 and num2.
  • We find the maximum of num1 and num2 using the conditional operator ?. This is necessary because we will start checking multiples from the larger of the two numbers.
  • We enter a while loop with a condition of 1 (which is always true) to iterate through possible multiples of the larger number.
  • Inside the loop, we check if both max % num1 and max % num2 are equal to 0. If they are, it means that max is a common multiple of both numbers, and we have found the LCM.
  • If we find the LCM, we print the result using printf and break out of the loop.
  • If we don't find the LCM in the current iteration, we increment max and continue the loop until we find it.
Output:



Tags:

Post a Comment

0Comments

Post a Comment (0)