Introduction
In this lab, we will explore the topic of prime numbers in JavaScript programming. Specifically, we will learn how to check whether a given number is a prime number or not using a simple algorithm. This knowledge can be useful in a variety of applications, such as cryptography, data security, and number theory.
Function to check if a number is prime
To practice coding, open the Terminal/SSH and type node. This function checks if a given integer is a prime number. Here are the steps to check if a number is prime:
- Check numbers from
2to the square root of the given number. - If any of them divides the given number, return
false. - If none of them divides the given number, return
true, unless the number is less than2.
Here's the code to implement this function in JavaScript:
const isPrime = (num) => {
const boundary = Math.floor(Math.sqrt(num));
for (let i = 2; i <= boundary; i++) {
if (num % i === 0) {
return false;
}
}
return num >= 2;
};
You can test the function by calling it with a number as an argument:
isPrime(11); // true
Summary
Congratulations! You have completed the Number Is Prime lab. You can practice more labs in LabEx to improve your skills.