How to create an algorithm to figure out if a number is a prime number or not
In this short guide, we will create an algorithm for checking if a number is a prime number or not. We will be using JavaScript as our language.
What is a prime number?
Before we start doing the work, we will just briefly explain what a prime number is. A prime number is a whole number that is greater than 1 and can only be divided by 1 or itself without getting any remainder.
- Example 10 can be divided with 2 and 5 without getting any remainder (not prime)
- Example 7 can only be divided with 1 and 7 without getting any remainder (prime)
Solution
In our solution, we will create a function that will accept a number as an argument, and then we will check that it is greater than 1 and that is is a whole number, and then we will check all numbers between 2-(n-1) that it cannot be divided without any rest. If it can, it means it is not a prime number.
const isPrime = (num) => { if (num <= 1 || !Number.isInteger(num)) { return false; } for (let i = 2; i < num; i++) { if (num % i === 0) { return false; } } return true; };
There we go. In our loop, we are using the modulus operation to check that the remainder is 0, if it is, it means it can be divided and then we return false. If it goes through the whole loop, we will assume it is a prime number.
Test it
Let's create a test for our function. We will print all the prime numbers from 0-100.
(() => { for (let i = 0; i < 100; i++) { if (isPrime(i)) { console.log(`${i} is a prime number`); } } })();
Result
Here is the log from our test run:
2 is a prime number 3 is a prime number 5 is a prime number 7 is a prime number 11 is a prime number 13 is a prime number 17 is a prime number 19 is a prime number 23 is a prime number 29 is a prime number 31 is a prime number 37 is a prime number 41 is a prime number 43 is a prime number 47 is a prime number 53 is a prime number 59 is a prime number 61 is a prime number 67 is a prime number 71 is a prime number 73 is a prime number 79 is a prime number 83 is a prime number 89 is a prime number 97 is a prime number
Outro
That's it for this guide. This type of problems are very typical for students that are on the journey of becoming software develelopers, and I hope this guide could give a helping hand with creating a prime number checker function.
Thanks for reading, and have a great day!