Introduction to Prime Numbers in JavaScript
A prime number is defined as an integer greater than one that has no divisors other than one and itself. Consequently, when a prime number is divided by any integer that is smaller than it, the result will never be a whole number. A common task in programming involves creating a program that checks whether a number is prime. This can be executed on the client side with JavaScript, allowing the client’s computer to perform the calculations. The subsequent article will outline the process of determining if a number is prime using JavaScript.
Logic
To determine whether a number is prime, we can perform divisions of that number by all integers starting from 1 up to but not including the number itself. If any of these divisions result in a remainder of zero, it indicates that the number is divisible by another integer and is consequently not classified as prime.
Let’s examine a few instances for enhanced understanding:
The number 13 can only be divided evenly by 1 and 13; for instance, if we attempt to divide it by another number such as 7, the result will yield a remainder of 6. In contrast, the number 12 possesses divisors including 1, 2, 3, 4, and 6, indicating that it is not classified as a prime number. It is noteworthy to mention that the smallest prime number is 2, and interestingly, it stands out as the sole even prime number.
Here are the first 20 primes:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
Numerous methods exist to determine whether a number is prime, collectively known as primality tests.
Methods to Test Prime Numbers in JavaScript
Example 1: Using For Loop
The most straightforward method to determine whether a number (which we will refer to as x) is prime involves checking for divisors (denoted as d) of x within the interval from 1 to < d < x. Also, we are aware that for any number x, there can never be divisors d such that d > x/2. Therefore, we will search for any integer within the range [2, x/2] that divides x evenly. If we identify such a number, we can conclude that x is not a prime number; if no divisors are found, then x is indeed prime.
<!DOCTYPE html>
<html>
<head>
<title>
Example for Prime Number Check in JavaScript using for loop
</title>
<style>
.results {
border : red 2px solid;
background-color : lightblue;
text-align : center;
padding-left : 15px;
height : 200px;
width : 95%;
}
.resultText {
font-size : 15px;
font-style : Aptos;
color : blue;
}
</style>
</head>
<body>
<div class = "results">
<h2> Enter the Number </h2>
Number: <input type = "number" name = "number" id = "number" required>
<button type = "button" onclick = "checkForPrime()" > Submit </button>
<div class = "resultText">
<p id = "result"> </p>
</div>
</div>
</div>
<script type = "text/javascript">
function checkForPrime() {
num = document.getElementById("number").value;
if(num == '' || num < 1) {
document.getElementById("result").style.color = "red";
document.getElementById("result").innerHTML = "Please Enter a Valid Number";
return;
}
var i;
var flag = true;
if (num == 1) {
flag = false;
} else {
for(i = 2; i < num-1; i++) {
if (num % i == 0) {
flag = false;
break;
}
}
}
if(flag == true) {
document.getElementById("result").style.color = "blue";
document.getElementById("result").innerHTML = "The number: " + num + " is a Prime Number";
} else {
document.getElementById("result").style.color = "red";
document.getElementById("result").innerHTML = "The number: " + num + " is NOT a Prime Number";
}
}
</script>
</body>
</html>
The function checkForPrime was invoked upon receiving the input value. Initially, we ensured that the user supplied legitimate input. The input must not be negative or left blank, as prime numbers cannot have negative values.
Subsequently, we employed a flag to check if, during the process of dividing the number by every integer ranging from 2 to n-1, we encountered a remainder of zero at any point.
Should we encounter a zero during our checks, this signifies that the number in question is not prime. Consequently, we would change the flag's status, exit the loop, and denote that number as non-prime. Conversely, if the flag's status remains unchanged, it suggests that we did not find any zero remainders, allowing us to classify that number as prime.
Output
Example 2: Using While Loop
This illustration demonstrates an alternative method of implementation in JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>
Example for Prime Number Check in JavaScript in while loop
</title>
<style>
.results {
border : red 2px solid;
background-color : pink;
text-align : left;
padding-left : 20px;
height : 200px;
width : 95%;
}
.resultText {
font-size : 25px;
font-style : normal;
color : blue;
}
</style>
</head>
<body>
<div class = "results">
<h2> Enter the Number </h2>
Number: <input type = "number" name = "number" id = "number" required>
<button type = "button" onclick = "checkForPrime()" > Submit </button>
<div class = "resultText">
<p id = "result"> </p>
</div>
</div>
</div>
<script type = "text/javascript">
function checkForPrime() {
num = document.getElementById("number").value;
// valid input checking
var i;
var flag = true;
if (num == 1) {
flag = false;
} else {
i = 2;
while (i < num/2) {
if(num % i == 0) {
flag = false;
break;
}
i++;
}
}
if(flag == true) {
document.getElementById("result").style.color = "blue";
document.getElementById("result").innerHTML = "The number: " + num + " is a Prime Number";
} else {
document.getElementById("result").style.color = "red";
document.getElementById("result").innerHTML = "The number: " + num + " is NOT a Prime Number";
}
}
</script>
</body>
</html>
Output
In this scenario, a while loop is utilized to assess the divisibility of the number, limiting the checks to n/2. This method is based on a mathematical principle which states that a number cannot be evenly divided by any integer greater than half of its value. By implementing this technique, we enhance efficiency by minimizing the total number of division operations needed.
Example 3: Using Recursion
<!DOCTYPE html>
<html>
<head>
<title>
Prime Number Check in JavaScript
</title>
<style>
.results {
border : green 1px solid;
background-color : aliceblue;
text-align : left;
padding-left : 20px;
height : 150px;
width : 95%;
}
.resultText {
font-size : 20px;
font-style : normal;
color : blue;
}
</style>
</head>
<body>
<div class = "results">
<h2> Enter the Number </h2>
Number: <input type = "number" name = "number" id = "number" required>
<button type = "button" onclick = "checkForPrime()" > Submit </button>
<div class = "resultText">
<p id = "result"> </p>
</div>
</div>
</div>
<script type = "text/javascript">
function checkForPrime() {
num = document.getElementById("number").value;
if(num == '' || num < 1) {
document.getElementById("result").style.color = "red";
document.getElementById("result").innerHTML = "Please Enter a Valid Number";
return;
}
var i = 2;
var flag = isPrime(num, i);
if(flag == true) {
document.getElementById("result").style.color = "blue";
document.getElementById("result").innerHTML = "The number: " + num + " is a Prime Number";
} else {
document.getElementById("result").style.color = "red";
document.getElementById("result").innerHTML = "The number: " + num + " is NOT a Prime Number";
}
}
// new recursive function
function isPrime( num, i) {
if(num < 2) {
return false;
}
if(num == 2) {
return true;
}
if(i > num/2) {
return true;
} else {
if( num % i == 0) {
return false;
} else {
return isPrime(num , i+1);
}
}
}
</script>
</body>
</html>
Output
In this context, a novel function utilizing recursion has been established. It incorporates base cases that align with the inherent reasoning, allowing the function to invoke itself repeatedly until these base cases are met. This function will take a number and systematically divide it by each divisor ranging from 2 to n-1, producing outcomes based on the resulting remainder.
Conclusion
- We have viewed the property number as prime and applied logic accordingly in JavaScript. We can apply different types of loops to achieve the same.
- Prime numbers are those which can only be divided by 1 and by themselves with no remainder.
- Prime numbers are discovered in JavaScript by iterating from numbers up to n and checking for divisors.