Languages
[Edit]
EN

JavaScript - different approaches to test if number is prime number

9 points
Created by:
Dollie-Rutledge
806

In this article, we would like to show different known approaches to check if given number is prime number using JavaScript.

 

Performace tests for the numbers from 0 to 100000 range:

Tested solutionHow fast is a solutuion?
Solution 1360x faster than Solution 2
Solution 2other solutions were compared to this one
Solution 317x faster than Solution 2
Solution 49x faster than Solution 2

Note: tests were made on Ryzen 9 and Google Chrome Web Browser.

 

Solution 1

Edit

In this solution, we check if the tested input number is divided by some number from 2 up to floor(sqrt(number)) range.

Complexity: O(sqrt(n))

 

Solution 2

Edit

In this solution, we count number of the tested number factors - expected 2 in prime number case.

Complexity: O(n)

 

Solution 3

Edit

In this solution, we check if the tested input number is divided by some number from 3 up to number (excluded) range.

Complexity: O(n/2)

 

Solution 4

Edit

In this solution, we check if the tested input number is divided by some number from 2 up to number (excluded) range.

Complexity: around O(n) - in practice algorithm ends job on factor detected.

 

See also

Edit
  1. JavaScript - finding prime numbers with Sieve of Eratosthenes

Other references

Edit
  1. Rabin primality test - Wikipedia
  2. Fermat primality test - Wikipedia

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join