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







<< PreviousNext >>

Perl Program to Calculate HCF (GCD) with User Input - Kids Fun Project



Understanding the HCF Algorithm in Perl

This Perl program calculates 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. we are to find.


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

All we need is a main code that asks the user for input.
For this purpose, we'll use the <STDIN>(<>) object.

How to use the HCF Code in Perl

The user gets to enter his/her choice of numbers for the HCF Perl algorithm.
After entering each number, the user presses <Enter>.
After the user has entered every of his/her numbers, the user enters the word done to see the result.


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


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 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 >>