In this example, we’ll learn to find Greatest Common Divisor (GCD) of two numbers in C#.
The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | static void Main(string[] args) { Console.Write(" Number 1 : "); int n1 = Convert.ToInt32(Console.ReadLine()); Console.Write(" Number 2 : "); int n2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(" ======================"); while (n1 != n2) { if (n1 > n2) n1 -= n2; else n2 -= n1; } Console.WriteLine(" G.C.D is " + n1); Console.ReadKey(); } |
When you run the program, the output will be: