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







<< PreviousNext >>

Perl Algorithm to Solve HCF (GCD) with User Input - Kids Fun Project



Find the Highest Common Factor (HCF) Using Perl

This interactive lesson shows you how to find the Highest Common Factor (HCF) — also known as the Greatest Common Divisor (GCD) — using Perl with user input. By entering your own numbers, you can see how a simple Perl algorithm calculates the HCF step by step.

This activity combines mathematics and programming, making it ideal for students who are learning basic coding concepts alongside number theory.

What Is the Highest Common Factor (HCF)? | Maths Explanation for Perl Kids

The Highest Common Factor of two numbers is the largest number that divides both values exactly, without leaving a remainder. For example, the HCF of 12 and 18 is 6.

Understanding HCF helps students build strong foundations in:

  • Factors and divisibility
  • Problem-solving skills
  • Logical and algorithmic thinking

Using Perl to Calculate HCF

In this example, Perl is used to create an interactive program that allows the user to enter several numbers. The program then checks which values divide both numbers evenly and identifies the highest one.

This approach demonstrates:

  • How to accept user input in Perl
  • How loops can be used to test factors
  • How math logic can be turned into working code

Understanding the HCF Algorithm in Perl

This Perl algorithm solves the HCF (Highest Common Factor) using user input and the Fast HCF Perl Code from the previous lesson.
Let's add some input mechanism so our user enters the set of numbers whose H.C.F. (G.C.D.) we are to find.


Combining the H.C.F. (G.C.D.) Perl Code and Collecting User Input

The code follows the same steps as that from the previous lessons.
We just adapted the HCF.html

How to use the HCF Code in Perl

The user gets to enter several numbers for the HCF Perl algorithm.
After entering each number, the user clicks the Next Number! button to enter the next number.
After the user enters the last number, with the last number still in the text box, the user clicks the Find H.C.F. button.


How the Perl HCF Algorithm Works

The Perl HCF algorithm follows these simple steps:

    1. Ask the user to enter several numbers. 2. Identify the smaller of the numbers. 3. Check each number from 1 up to the smaller value. 4. Find the largest number that divides all inputs exactly. 5. Display the result as the HCF.

This method is easy to understand and well suited for beginners learning how algorithms work.

HCF vs GCD Explained | Maths Explanation for Perl Kids

You may see both HCF (Highest Common Factor) and GCD (Greatest Common Divisor) used in math and programming. They mean the same thing—the largest number that divides two values exactly.

In Perl programming, both terms are commonly used when writing math algorithms.


Why Learn HCF Through Perl?

Learning to calculate HCF using Perl helps students:

  • Connect math concepts to real code
  • Practice logical thinking and debugging
  • Gain confidence with basic programming structures
  • Learn by doing, not just reading

This makes it an excellent math coding project for primary and early secondary students.

Who Is This Perl HCF-with-input Algorithm Lesson For?

This interactive Perl HCF lesson is suitable for:

  • Primary and junior secondary school students
  • Teachers introducing coding with math
  • Beginners learning Perl through practical examples
  • Anyone interested in interactive math programming

Summary: HCF with User Input Algorithm in Perl

This page demonstrates how to:

  • Find the Highest Common Factor using Perl
  • Use user input to create an interactive program
  • Apply math logic through a simple Perl algorithm
  • Learn coding and mathematics together in a practical way

Try the example, explore the code, and use this project as a foundation for more advanced math and programming challenges.

So! Perl Fun Practice Exercise - Find HCF with User Input

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









Perl Code for Fast HCF - Module File.

package FASTHCF;

BEGIN {
    require Exporter;

    # for the sake of standard
    our $VERSION = 2016.12;

    # Inherit from exporter to export functions and variables
    our @ISA = qw(Exporter);

    # Functions and variables to be exported by default
    our @EXPORT_OK = qw(getHCF);
}

use warnings;
use strict;
use Carp qw(croak);

my ($index$all_round_factor$calc_result);
my (@set_of_numbers@arg_copy@common_factors@minimal_prime_factors);

# simulate an object construct
# takes one argument  -- besides its package name;
# reference to set whose HCF is to found
sub new {
    no warnings;
    
    my $this = shift;
    my $parameters = {@_};
    bless $parameters$this;
    $this->_init(@_);
    return $this;
}

# Simulate a constructor
sub _init {
    my $self = shift;
    
    my $tmp = shift;
    @common_factors = ();
    @set_of_numbers = @{$tmp};
    # STEP 1:
    @set_of_numbers = sort {$a <=> $b@set_of_numbers;

    @arg_copy = @set_of_numbers;

    $index = 2;
    $all_round_factor = 0# state flag
    $calc_result = 1;
}

# STEP 2:
# does the grunt work
# takes no arguments but requires '@set_of_numbers' to be set
sub findHCFFactors {
    while ($index < scalar @minimal_prime_factors) {
        $all_round_factor = 1;
        # STEP 3:
        for (0 .. $#set_of_numbers) {
            $all_round_factor = 0 if !($all_round_factor &&
                    $arg_copy[$_] % $minimal_prime_factors[$index] == 0);
        }
        # STEP 4:
        if ($all_round_factor) {
            $arg_copy[$_] /= $minimal_prime_factors[$indexfor 0 .. $#set_of_numbers;
            push @common_factors$minimal_prime_factors[$index];
        }
        $index++;
    }
    return;
}

# Returns a scalar value of the HCF
sub getHCF {
    require LISTPRIMEFACTORS or croak "Error $! occurred.";
    my $aux = LISTPRIMEFACTORS->new($set_of_numbers[0]);
    @minimal_prime_factors = @{$aux->onlyPrimeFactors()};

    $index = 0;
    findHCFFactors();

    #iterate through and retrieve members
    for (@common_factors) {
        $calc_result *= $_;
    }

    return $calc_result;
}


1;


Perl Code for HCF with User Input - Main Class.

#!/usr/bin/perl;
use strict;
use warnings;
use FASTHCF qw(getHCF);

# Useful variables
my ($lower_boundary$upper_boundary$test_guy$answer);
my @set;

# Collect input
print "\nWelcome to our Find HCF program.\n";
print "Enter your series of numbers whose HCF you wish to find.\n";
print "\nType 'done' when you are through with entering your numbers.\n";
print "Enter First Number:  ";

@set = ();
my $user_num;

eval {
    do {
        # get keyboard input
        $user_num = <>;
        chomp $user_num;
        # Convert 'user_num' to upper case.
        $user_num = uc $user_num;
        # Make sure input is a number
        if ($user_num =~ /[0-9]+/) {
            if ($user_num != 0) {
                push @set$user_num;
                print "Enter Next Number:  ";
            } else {
                print "\nYou cannot enter zero. Repeat that!\nType 'done' when you're finished.\n";
            }
        } elsif ($user_num ne "DONE") {
            print "\nWrong Input. Repeat that!\nType 'done' when you're finished.\n";
        }
    } while ($user_num ne "DONE");
};

# Use the fast HCF module/class
my $h_c_f = FASTHCF->new(\@set);
$answer = $h_c_f->getHCF();
print ("The H.C.F. of "join(", "@set), " is $answer\n");


print "\n\n";




<< PreviousNext >>