javascript
Parameters: number
The function expects a single integer as its parameter
Returns: A boolean indicating if the input is a prime number
checkPrime function uses the mathematical principle of number theory to check if a given integer is prime or not.
Greetings, programmer! This blog post is about to guide you through creating a function in Javascript, specifically designed to check if a number is prime or not. There will be concrete steps below, which will provide you fundamental knowledge of programming this function. Get ready to delve into the engaging world of Javascript functions!
The first step in solving this problem is to understand what a prime number is. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function check-prime should therefore determine whether a given number is prime or not.
function checkPrime(num) {
// We will implement our code inside this function
}
We know that numbers less than 2 are not prime so we can handle this edge case first. If the input number is less than 2, our function should return false.
function checkPrime(num) {
if (num < 2) {
return false;
}
}
Next we need to check if the number is divisible by any other number apart from itself and 1. We'll create a loop from 2 up to the square root of the number. If our number is divisible by any of these numbers then it is not prime and we should return false.
function checkPrime(num) {
if (num < 2) {
return false;
}
for(let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
}
If the number is not divisible by any number in our loop then it must be prime. At the end of our function we will therefore add a line to return true.
function checkPrime(num) {
if (num < 2) {
return false;
}
for(let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
The function checkPrime
successfully checks whether a number is prime or not using a simple for loop and the modulus operator to check divisibility. Remember that we only needed to loop up to the square root of the number because a larger factor of the number would be a multiple of smaller factor that has already been checked.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The `checkPrime` function uses this principle to determine if a number is prime by checking if it has any other divisors beyond 1 and itself.
Learn more