Find the Highest Common Factor (HCF) Using JavaScript
This interactive lesson shows you how to find the Highest Common Factor (HCF) — also known as the Greatest Common Divisor (GCD) — using JavaScript with user input. By entering your own numbers, you can see how a simple JavaScript 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 JavaScript 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 JavaScript to Calculate HCF
In this example, JavaScript 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 JavaScript
- How loops can be used to test factors
- How math logic can be turned into working code
Understanding the HCF Algorithm in JavaScript
This JavaScript algorithm solves 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 several numbers for the HCF JavaScript 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.
Create 1 new file; On Notepad++: File, New.
Call it HCFInput.html
Type out the adjoining JavaScript code for collecting input for H.C.F. (G.C.D.).
How the JavaScript HCF Algorithm Works
The JavaScript 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 JavaScript 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 JavaScript programming, both terms are commonly used when writing math algorithms.
Why Learn HCF Through JavaScript?
Learning to calculate HCF using JavaScript 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 JavaScript HCF-with-input Algorithm Lesson For?
This interactive JavaScript HCF lesson is suitable for:
- Primary and junior secondary school students
- Teachers introducing coding with math
- Beginners learning JavaScript through practical examples
- Anyone interested in interactive math programming
Summary: HCF with User Input Algorithm in JavaScript
This page demonstrates how to:
- Find the Highest Common Factor using JavaScript
- Use user input to create an interactive program
- Apply math logic through a simple JavaScript 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! 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 for Fast HCF - .js
var index = 0; // index into array common_factors
var state_all_round_factor = false; // variable to keep state
var found_prime_factors = [];
var count = 0; // index into array 'found_prime_factors'
/* Pass of Array(according to javascript) is by reference;
so make a copy that will be passed instead. */
var arg_copy = [];
var i;
// STEP 2:
/*
Compiles only the factors of the smallest member of 'group_of_numbers'
*/
function onlyPrimeFactors(sub_level) {
var temp_limit = Math.ceil(Math.sqrt(sub_level));
while (i <= temp_limit) {
if (i != 1 && (sub_level % i) == 0) { // avoid an infinte loop with the i != 1 check.
found_prime_factors[count++] = i;
return onlyPrimeFactors(sub_level / i);
}
i++;
}
found_prime_factors[count] = sub_level;
return;
}
/*
* Our function checks 'group_of_numbers';
* If it finds a factor common to all fo it, it records this factor;
* then divides 'group_of_numbers' by the common factor found
* and makes this the new 'group_of_numbers'.
* It continues recursively until all common factors are found.
*/
function getHCFFactors(operate_on) {
while (i < found_prime_factors.length) {
state_all_round_factor = true;
// STEP 3:
for (var j = 0; j < operate_on.length; j++) {
if (state_all_round_factor == true && (operate_on[j] % found_prime_factors[i]) == 0) {
state_all_round_factor = true;
} else {
state_all_round_factor = false;
}
}
// STEP 4:
if (state_all_round_factor == true) {
for (var j = 0; j < operate_on.length; j++) {
operate_on[j] /= found_prime_factors[i];
}
common_factors[index++] = found_prime_factors[i];
}
i++;
}
return;
}
function getFastHCF(group) {
// STEP 1:
// Sort in ascending order
group_of_numbers.sort(
function (a, b) {
return a - b;
}
);
i = 2; // start checking for factors from variable 2
onlyPrimeFactors(group[0]);
for (var j = 0; j < group.length; j++) {
arg_copy[j] = group[j];
}
i = 0;
getHCFFactors(arg_copy); // call to our function
var HCF = 1;
for (var k = 0; k < common_factors.length; k++) {
HCF *= common_factors[k];
}
return HCF;
}
JavaScript Code with User Input for HCF with Input - .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>