Understanding the HCF Algorithm in JavaScript
This JavaScript program calculates the HCF (Highest Common Factor) using user input and
the Fast HCF JavaScript 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.) JavaScript 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 JavaScript
The user gets to enter his/her choice of numbers for the HCF JavaScript algorithm.
After entering each number, the user clicks the
Next Number! button to enter his/her number.
After the user enters his/her last number, with the last
number still in the text box, the user clicks the
Find H.C.F. button.
Create 1 new file; On Notepad++: File, New.
Call them HCFInput.html
Type out the adjoining JavaScript code for collecting input for H.C.F. (G.C.D.).
So! JavaScript 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 JavaScript code finds the HCF of your input numbers.
JavaScript Code with User Input for HCFInput.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Find H.C.F.</title>
<script src="FastHCF.js"></script>
</head>
<body>
<h4>Highest Common Factors of a Group of Numbers.</h4>
<br/>
<div id="myHCF">Your result is displayed here...</div>
<script>
var group_of_numbers = [];
var input;
var input_instruction = "Enter first number: ";
var hold = "";
var j = 0;
alert("Welcome to our bot!");
do {
// get keyboard input
input = prompt(input_instruction, "");
// Convert 'user_input' to upper case.
input = input.toUpperCase();
// Make sure input is a number
if (/[0-9]+/.test(input)) {
if (input != 0) {
group_of_numbers[j] = parseInt(input);
hold += group_of_numbers[j] + "; "
input_instruction = hold + "seen! \nType 'done' when you're finished \nNow Enter Next Number: ";
j++;
} else {
alert("You cannot enter zero. Repeat that!\nType 'done' when you're finished.");
}
} else if (input != "DONE") {
alert("Wrong Input. Repeat that!\nType 'done' when you're finished.\n");
}
} while (input != "DONE");
var result = getFastHCF(group_of_numbers);
document.getElementById("myHCF").innerHTML =
"The H.C.F. of " + group_of_numbers.join(", ") + " is: " + result;
</script>
</body>
</html>