Skip to main content

Create a function that takes two numbers and returns the highest common factor

   1:  using System;
   2:  namespace st
   3:  {
   4:      class HCF
   5:      {
   6:          public static void Main()
   7:          {
   8:              Console.WriteLine(Hcf(30, 55));
   9:              Console.WriteLine(Hcf(28, 27));
  10:          }
  11:          public static int Hcf(int n1, int n2)
  12:          {
  13:              // start the loop from half of the smallest of two numbers 
  14:              for (int i = n1 < n2 ? n1 / 2 : n2 / 2; i > 1; i--)
  15:              {
  16:                  if (n1 % i == 0 && n2 % i == 0)
  17:                      return i;  // found Highest common factor
  18:              } // for
  19:   
  20:              return 1;  // Didn't find highest common factor, so 1 is treated as so
  21:          } // HFC
  22:   
  23:      }  // class
  24:   
  25:  } // namespace



Comments