Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

HCF and LCM using recursion in C#

The following code explains how to calculate HCF and LCM using C# with recursive calling.

  1. using System;
  2. using System.Text;
  3.  
  4. namespace forgetCode
  5. {
  6.  
  7. class program
  8. {
  9. public static void Main()
  10. {
  11. long x, y, hcf, lcm;
  12.  
  13. Console.WriteLine("Enter two integers");
  14. x = Convert.ToInt64(Console.ReadLine());
  15. y = Convert.ToInt64(Console.ReadLine());
  16.  
  17. hcf = gcd(x, y);
  18. lcm = (x * y) / hcf;
  19.  
  20. Console.WriteLine("Greatest common divisor of {0} and {1} = {2}\n", x, y, hcf);
  21. Console.WriteLine("Least common multiple of {0} and {1} = {2}\n", x, y, lcm);
  22.  
  23. }
  24.  
  25. static long gcd(long a, long b)
  26. {
  27. if (b == 0)
  28. {
  29. return a;
  30. }
  31. else
  32. {
  33. return gcd(b, a % b);
  34. }
  35. }
  36.  
  37. }
  38. }


Output:

Enter two integers
8
12
Greatest common divisor of 8 and 12 = 4

Least common multiple of 8 and 12 = 24