LCM of 2 Numbers- The least common multiple (LCM) of two or more numbers is the smallest number (not counting 0) which is a multiple of all of the numbers.
Let’s take an Example for calculating the LCM of 12 and 8.
break down 12 and 8 into prime factors:
prime factors of 12= 2*2*3
prime factors of 8= 2*2*2
the highest factor for number 12 is 3
the highest factor for number 8 is 2
now take the highest power of each prime factor in the prime factorization and multiply them:
=3 *power(2,3)
=3*8
=24
C# program to find the LCM of 2 numbers.
Method-1
Code
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter First Number");
bool flag=false;
int n1,n2;
flag = int.TryParse(Console.ReadLine(), out n1);
if(n1<0)
{
Console.WriteLine("Number should not be negative");
return;
}
flag = false;
Console.WriteLine("Please Enter Second Number");
flag = int.TryParse(Console.ReadLine(), out n2);
if (n2 < 0)
{
Console.WriteLine("Number should not be negative");
return;
}
// // maximum number between n1 and n2 is stored in minMultiple
int minvalue = Math.Min(n1, n2);
while(true)
{
if(minvalue%n1==0 && minvalue%n2==0)
{
break;
}
minvalue++;
}
Console.WriteLine("LCM of {0} and {1} is {2}" ,n1,n2,minvalue);
}
}
Output
Please Enter First Number
11
Please Enter Second Number
22
LCM of 11 and 22 is 22
Method-2
Code
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter First Number");
bool flag = false;
int n1, n2;
flag = int.TryParse(Console.ReadLine(), out n1);
if (n1 < 0)
{
Console.WriteLine("Number should not be negative");
return;
}
flag = false;
Console.WriteLine("Please Enter Second Number");
flag = int.TryParse(Console.ReadLine(), out n2);
if (n2 < 0)
{
Console.WriteLine("Number should not be negative");
return;
}
int minvalue = Math.Min(n1, n2);
int gcd=1;
for (int i = 1; i <= n1 && i<=n2; i++)
{
// // Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
{
gcd = i;
}
}
int lcm = (n1 * n2) / gcd;
Console.WriteLine("LCM of {0} and {1} is {2}", n1, n2, lcm);
}
}
Output
Please Enter First Number
11
Please Enter Second Number
22
LCM of 11 and 22 is 22
Method-3
Code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter First Number");
bool flag = false;
int n1, n2;
flag = int.TryParse(Console.ReadLine(), out n1);
if (n1 < 0)
{
Console.WriteLine("Number should not be negative");
return;
}
flag = false;
Console.WriteLine("Please Enter Second Number");
flag = int.TryParse(Console.ReadLine(), out n2);
if (n2 < 0)
{
Console.WriteLine("Number should not be negative");
return;
}
int numerator = Math.Max(n1, n2);
int denominator = Math.Min(n1, n2);
int remainder = numerator % denominator;
//check the remainder value is zero after divsion operation
while(remainder!=0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
int gcd = denominator;
int lcm = (n1 * n2) / gcd;
Console.WriteLine("LCM of {0} and {1} is {2}", n1, n2, lcm);
}
}