usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Finding HCF and GCD in C# - Kids Fun Exercise



What is HCF and GCD? | Maths Explanation for C# Kids

Highest Common Factor or Greatest Common Divisor is the highest-valued-factor or greatest-valued-divisor common to a set of numbers.

In this C# math project, we'll explore how to find the Highest Common Factor (HCF) and Greatest Common Divisor (GCD) of numbers. This tutorial is perfect for primary school students learning to code with C#.

A common method for finding H.C.F. - G.C.D. is repeated factorization using only common factors.

If we have the set of numbers 30, 48 and 54 for example, their H.C.F. or G.C.D. is found thus:

Steps for calculating HCF using factorization method in C#
Figure: Math steps for calculating HCF using factorization method in C#.

Hence, H.C.F. of 30, 48 and 54 = 2 X 3 = 6


How to find HCF of multiple numbers in C# | Step-by-step Guide.

We shall follow the steps below in our C# algorithm for finding HCF.

Step 1:

Do a numerical sort on the set so its first member is the smallest in the set.

Step 2:

Starting with 2, iteratively check through the set of numbers for a common factor.

Step 3:

For each common factor, divide every member of the number set by the common factor.

Step 4:

Repeat from step 2 recursively until there are no more common factors.

Create a new C# class file; Project, Add Class.
Call it HCF.
Type out the adjoining C# code for finding Highest Common Factor (H.C.F.) or Greatest Common Divisor.



Note: You can comment out the C# code for the main class from the previous lesson if you have been following.


So! C# Fun Practice Exercise - Find HCF

As a fun practice exercise, feel free to try out your own numbers, and see how the C# code finds the HCF of those numbers.







C# Code for HCF class.

using System.Collections.Generic;

namespace Arithmetic
{
    class HCF
    {
        private int[] set_of_numbers;
        private List<int> common_factors = new List<int>(); // factors common to our set_of_numbers

        private int index; // index into array common_factors
        private bool all_round_factor; // variable to keep state
        private int calc_result; // helps calculate H.C.F.

        public HCF(List<int> group)
        {
            set_of_numbers = new int[group.Count];
            index = 0;

            // STEP 1:
            group.Sort();

            //iterate through and retrieve members
            foreach (int number in group)
            {
                set_of_numbers[index] = number;
                index++;
            }

            index = 2;
            all_round_factor = false;
            calc_result = 1;
        }

        /**
         * Our function checks 'set_of_numbers'; If it finds a factor common to
         * all for it, it records this factor; then divides 'set_of_numbers' by the
         * common factor found and makes this the new 'set_of_numbers'. It
         * continues recursively until all common factors are found.
         */

        private int findHCFFactors()
        {
            while (index <= set_of_numbers[0])
            {
                // Check for factors common to every member of 'set_of_numbers'
                all_round_factor = true;
                // STEP 2:
                for (int j = 0; j < set_of_numbers.Length; j++)
                {
                    if (!(all_round_factor == true && set_of_numbers[j] % index == 0))
                    {
                        all_round_factor = false;
                    }
                }
                // STEP 3:
                // Divide every member of 'set_of_numbers by each common factor
                if (all_round_factor == true)
                {
                    for (int j = 0; j < set_of_numbers.Length; j++)
                    {
                        set_of_numbers[j] /= index;
                    }
                    common_factors.Add(index);
                    // STEP 4:
                    return findHCFFactors();
                }
                index++;
            }

            return 0;
        }

        /**
         * Just calls out and collects the prepared factors.
         * @return - string value
         */

        public int getHCF()
        {
            findHCFFactors();

            //iterate through and retrieve members
            foreach (int factor in common_factors)
            {
                calc_result *= factor;
            }

            return calc_result;
        }
    }
}

C# Code for HCF - Main Class.

using System;
using System.Collections.Generic;

namespace Arithmetic
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to our demonstration sequels");
            Console.WriteLine("Hope you enjoy (and follow) the lessons.");
            Console.WriteLine("\r\n");

            /*
            * Find HCF.
             */

            List<int> set = new List<int>();
            set.Add(30);
            set.Add(48);
            set.Add(54);

            HCF hcf = new HCF(set);

            Console.WriteLine("The H.C.F. of " + String.Join(", ", set) + " is " + hcf.getHCF());

        }
    }
}



<< PreviousNext >>