Author : Rahul
Write a program to calculate GCD or HCF of two numbers.
GCD or HCF
The HCF or GCD of two numbers is the largest number which can fully divide both numbers. For example, the GCD or HCF of 20 and 30 is 10.
Program
using System;
namespace ProgrammingQuestion
{
class Program
{
static void Main(string[] args)
{
//Variable Declaration
string firstNumberVal, secondNumberVal;
int firstNumber, secondNumber, GCD = 1, minNumber;
//User Input
Console.Write("Enter First Number:");
firstNumberVal = Console.ReadLine();
firstNumber = Convert.ToInt32(firstNumberVal);
Console.Write("Enter Second Number:");
secondNumberVal = Console.ReadLine();
secondNumber = Convert.ToInt32(secondNumberVal);
//GCD or HCF Logic
if(firstNumber < secondNumber)
{
minNumber = firstNumber;
}
else
{
minNumber = secondNumber;
}
for (int i = 1; i <= minNumber/2; i++)
{
if (firstNumber % i == 0 && secondNumber % i == 0)
{
GCD = i;
}
}
//Print Result
Console.WriteLine($"GCD of {firstNumber} and {secondNumber} is {GCD}.");
Console.Read();
}
}
}
Output
Enter First Number:30
Enter Second Number:40
GCD of 30 and 40 is 10.