Prime Tester
cehsu
5,074 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
The goal today is to write a function that determines whether a number is prime.
Check if a number is prime
Write an isPrime
function that takes a number as parameter and returns true if this number is prime, false if it isn't.
Reminder: A prime number:
- Can only be divided by
1
and itself - Is greater than
1
Write the isPrime function
1
2
3
4
5
6
7
8
9
10
11
12
13
function isPrime (number) {
return false;
// For demo purpose:
/*
var start = 2;
while (start <= Math.sqrt(number)) {
if (number % start++ < 1) return false;
}
return number > 1;
*/
}
module.exports = isPrime;
Enter to Rename, Shift+Enter to Preview
Optimize
Take a look at the Sieve of Eratosthenes. How much faster did your implementation of the sieve run? How can you account for this in terms of time complexity?
See:
https://github.com/AlgorithmsMeetup/GetAllPrimes
How about non-deterministic approaches?
See:
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content