In this program, 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 | static void Main(string[] args) { int n1 = 54, n2 = 81, 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; } Console.Write (" G.C.D of {0} and {1} is {2}", n1, n2, gcd); Console.ReadKey(); } |
When you run the program, the output will be: