What are Prime Factors? | Maths Explanation for JavaScript Kids
Finding prime factors is all about selecting those factors of
a number that are prime.
The prime factors of 36 as an example, are:
In this guide, we'll thoroughly explain prime factorisation and show
how to code a JavaScript algorithm to find prime-factors in a detailed and interactive manner.
This Math exercise and JavaScript algorithm will help young students
understand prime factorization by listing all prime factors of a number.
Step-by-step Guide to Prime Factorisation of Numbers in JavaScript
We'll go about the JavaScript algorithm to find prime factors in a simple way:
Step 1:
Starting with 2, find the first factor of the number of interest
- this factor will definitely be a prime.
Store this factor away.
Step 2:
Divide number in question by found factor.
Step 3:
Using result from Step 2 as the new number in question (number whose prime factors we are trying to find), repeat Step 1.
Step 4:
Continue recursively until we arrive at 1.
Step 5:
We'll use the square-root of number range.
Create a new file; On Notepad++: File, New.
Call it PrimeFactors.html.
Type out the adjoining JavaScript code for listing prime factors.
Now JavaScript functions come in handy, don't they?
So! JavaScript Fun Practice Exercise - List Prime Factors
As a fun practice exercise, feel free to try out your own different numbers, and see how the JavaScript code lists the prime factors of those numbers.
JavaScript Code for Prime Factors
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Listing The Prime Factors Of A Number.</title>
</head>
<body>
<h4>Prime factors constitutes those factors of a number that are prime.</h4>
<div id="prime_factors"></div>
<script>
var find_my_factors = 48;
var found_prime_factors = [];
var count = 0; // index into array 'found_prime_factors'
var i = 2; // variable for our function loop
onlyPrimeFactors(find_my_factors); // Call our function
/* If variable find_my_factors is a prime number(has no factors), we simply say so. */
document.getElementById("prime_factors").innerHTML = found_prime_factors.length > 1 ?
"The prime factors of " + find_my_factors + " are: <br />" + found_prime_factors.join(" X ") :
find_my_factors + " has no other factors except 1 and itself. It is a prime number.";
/*
* Our function checks 'find_my_factors';
* If it finds a factor, it records this factor,
* then divides 'find_my_factors' by the found factor
* and makes this the new 'find_my_factors'.
* It continues recursively until all factors are found.
*/
function onlyPrimeFactors(sub_level) {
//STEP 5
var temp_limit = Math.ceil(Math.sqrt(sub_level));
//STEP 1
while (i <= temp_limit) {
if (i != 1 && (sub_level % i) == 0) { // avoid an infinite loop with the i != 1 check.
found_prime_factors[count++] = i;
//STEPS 2, 3, 4
return onlyPrimeFactors(sub_level / i);
}
i++;
}
found_prime_factors[count] = sub_level;
return;
}
</script>
</body>
</html>