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







<< PreviousNext >>

Finding HCF and GCD in Java - Kids Fun Exercise



What is HCF and GCD? | Maths Explanation for Java 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 Java 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 Java.

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 Java
Figure: Math steps for calculating HCF using factorization method in Java.

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


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

We shall follow the steps below in our Java 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 Java class file; File, New File.
Call it findHCF.
Type out the adjoining Java code for finding Highest Common Factor (H.C.F.) or Greatest Common Divisor.


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


So! Java Fun Practice Exercise - Find HCF

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







Java Code for find HCF class.

package arithmetic;

import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;

public class HCF {

    private final int[] set_of_numbers;
    private final List<Integer> common_factors = new ArrayList<>(); // factors common to our set_of_numbers

    private int index// index into array common_factors
    private boolean all_round_factor// variable to keep state
    private int calc_result// helps calculate HCF
    private Comparator c// object for sorting arrays

    public HCF(List<Integer> group) {
        set_of_numbers = new int[group.size()];
        index = 0;
        
        group.sort(c);
        
        //iterate through and retrieve members
        for (int number : group) {
            set_of_numbers[index] = number;
            index++;
        }
        
        index = 2;
        all_round_factor = false;
    }

    /**
     * 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;
            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;
                }
            }
            // 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);
                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
        calc_result = 1;
        common_factors.stream().forEach((factor) -> {
            calc_result *= factor;
        });
        
        return calc_result;
    }
}

Java Code for find HCF - Main Class.

package arithmetic;

import java.util.ArrayList;
import java.util.List;

public class Arithmetic {

    public static void main(String[] args) {
        System.out.println("Welcome to our demonstration sequels");
        System.out.println("Hope you enjoy (and follow) the lessons.");
        System.out.println("");

        /*
        * Find HCF.
         */

        String render_result = "The HCF of ";
        HCF hcf;
        List<Integer> set;

        set = new ArrayList<>();
        set.add(30);
        set.add(48);
        set.add(54);

        for (int number : set) {
            render_result += number + "; ";
        }
        render_result += "is:  ";

        hcf = new HCF(set);
        System.out.println(render_result + hcf.getHCF());
    }

}



<< PreviousNext >>