Find prime number algorithm in Javascript
Prime number is one of the most famous algorithms ever, Mathematically it is easy to find the prime number but when it comes to writing code for this some of you may face challenges. Let me introduce you to the Prime number.
Statement
You are given an integer N. You need to print the series of all prime numbers till N.
1, 2, 3, 4, 5, 6, 7, 8………N
As per the definition we know if a number divided exactly only by itself and 1 then it’s a prime number
Implementation
isPrime is the function that returns true or false on the basis of the number we passed is prime or not. If isPrime returns true then we push it into the array. In the end, we have an array of prime integers up to a given number N.
This is probably the first solution that will come to your mind. The important part here is that we calculate prime numbers using the concept if the number is divided by 1 and the number itself then we return true(It’s a prime number) else we return false(not a prime number).
we can also have other optimal solution by reducing its time complexity.
Conclusion
This was just an example of how to design an algorithm, in this case, it was the prime number sequence, which is simple enough to understand and we can also boost this algorithm just with some small changes.