To tell if a Number in JavaScript is prime, we can use the modulus (remainder) operator % along with an if conditional statement. We can make a simple function that will let us know if a number is prime or not. First, here is the JavaScript code that determines whether a number is prime or not.
for (var i = 2; i < num; i++){
if (num % i == 0){
// Number is NOT prime
}
}
if (num > 1){
// Number IS prime
} else {
// Number is NOT prime
}
num in the code above would be the number we want to check is prime or not.
We can put this code into a function so that we only have to enter a number into our function to see if it is prime. The function will return true if the number is prime, and false if the number is not prime.
function isPrime(num) {
for (var i = 2; i < num; i++){
if (num % i == 0){
// Number is NOT prime
return false;
}
}
if (num > 1){
// Number IS prime
return true;
} else {
// Number is NOT prime
return false;
}
}
Tell if a Number in JavaScript is Prime with a Click
Below we will provide code to let the user input a number, and then use the our function above to tell if the number is prime or not. Here is our simple HTML setup:
Type a whole number to know if it’s prime:
First, we will add an onclick event to the submit button to run a function we will create.
We will then use the value property along with the getElementById method to get the value of the input.
We will then determine if the number is prime using the function we created isPrime() above. We will add to our function above so that we can display the results to the user.
Finally, we will display the results using the textContent property.
function isPrime(){
//Get the user input
var num = Number(document.getElementById("userVal").value);
//Check if the number is prime and display the results
var result = true;
for (var i = 2; i < num; i++){
if (num % i == 0){
// Number is NOT prime
result = false;
document.getElementById("results").textContent = num + " is NOT Prime.";
}
}
if (num > 1 && result != false){
// Number IS prime
document.getElementById("results").textContent = num + " is Prime.";
} else {
// Number is NOT prime
document.getElementById("results").textContent = num + " is NOT Prime.";
}
}
The final code and output for this example are below:
Code Output:
Type a whole number to know if it’s prime:
Full Code:
Type a whole number to know if it’s prime:
Hopefully this article has been useful in helping you tell if a number in JavaScript isprime.