C# program to find GCD and LCM
Here's a C# program to find the greatest common divisor (GCD) and least common multiple (LCM) of two numbers:
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int gcd = FindGCD(num1, num2);
int lcm = FindLCM(num1, num2);
Console.WriteLine($"GCD of {num1} and {num2} is: {gcd}");
Console.WriteLine($"LCM of {num1} and {num2} is: {lcm}");
}
static int FindGCD(int num1, int num2)
{
while (num2 != 0)
{
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}
static int FindLCM(int num1, int num2)
{
int gcd = FindGCD(num1, num2);
int lcm = (num1 * num2) / gcd;
return lcm;
}
}
In this program, the FindGCD method takes two integers num1 and num2 as input and calculates their greatest common divisor (GCD) using the Euclidean algorithm. It repeatedly divides the larger number by the smaller number and updates the values until the remainder becomes zero. At that point, the GCD is the remaining non-zero number.
The FindLCM method takes the same two integers num1 and num2 as input and calculates their least common multiple (LCM) using the GCD. It first calculates the GCD using the FindGCD method and then calculates the LCM using the formula (num1 * num2) / GCD.
The Main method prompts the user to enter two numbers, calls the FindGCD and FindLCM methods with the user inputs, and displays the calculated GCD and LCM.
Note that the program assumes the user will input valid integers. It doesn't handle exceptions if the input is not a valid integer.