Naturally, for bool isprime(number)
there would be a data structure I could query.
I define the best algorithm, to be the algorithm that pr
A prime number is any number that is only divisible by 1 and itself. All other numbers are called composite.
The simplest way, of finding a prime number, is to check if the input number is a composite number:
function isPrime(number) {
// Check if a number is composite
for (let i = 2; i < number; i++) {
if (number % i === 0) {
return false;
}
}
// Return true for prime numbers
return true;
}
The program has to divide the value of number
by all the whole numbers from 1 and up to the its value. If this number can be divided evenly not only by one and itself it is a composite number.
The initial value of the variable i
has to be 2 because both prime and composite numbers can be evenly divided by 1.
for (let i = 2; i < number; i++)
Then i
is less than number
for the same reason. Both prime and composite numbers can be evenly divided by themselves. Therefore there is no reason to check it.
Then we check whether the variable can be divided evenly by using the remainder operator.
if (number % i === 0) {
return false;
}
If the remainder is zero it means that number
can be divided evenly, hence being a composite number and returning false.
If the entered number didn't meet the condition, it means it's a prime number and the function returns true.