In this example, we’ll learn to find the Greatest Common Divisor or HCF using a recursive function in C#.
The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).
This program takes two positive integers and calculates G.C.D using recursion.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static int Hcf(int n1, int n2) { if (n2 != 0) return Hcf(n2, n1 % n2); else return n1; } static void Main(string[] args) { int n1 = 100, n2 = 60; int hcf = Hcf(n1, n2); Console.Write("Greatest Common Divisor (G.C.D) of {0} and {1} is {2}.", n1, n2, hcf); Console.ReadKey(); } |
When you run the program, the output will be: