C# Return the H.C.F. of a Given Number

The Highest Common Factor (H.C.F.) of two (or more) numbers is the largest number that divides evenly into both numbers.

Example:

The common factors or of 12 and 18 are 1, 2, 3 and 6.

The largest common factor is 6, so this is the H.C.F. of 12 and 18.

 

using System;

namespace Program
{
    class Program
    {
        public static void Main(string[] args)
        {
            int num1, num2, i, hcf = 0;

            Console.Write("Enter the First Number: ");
            num1 = Convert.ToInt16(Console.ReadLine());

            Console.Write("\nEnter the Second Number: ");
            num2 = Convert.ToInt16(Console.ReadLine());

            for (i = 1; i <= num1 || i <= num2; ++i)
            {
                if (num1 % i == 0 && num2 % i == 0)
                {
                    hcf = i;
                }
            }

            Console.Write("\nCommon Factor is: ");
            Console.WriteLine(hcf);

            Console.Read();
        }
    }
}

 

Output