Skip to content

Instantly share code, notes, and snippets.

@yopefonic
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save yopefonic/cb32a6d8e3a13d5999a3 to your computer and use it in GitHub Desktop.

Select an option

Save yopefonic/cb32a6d8e3a13d5999a3 to your computer and use it in GitHub Desktop.
primes between X and Y
// assignment:
// Return all prime numbers between $nMin and $nMax (where $nMin and $nMax are arguments
// supplied to your function)*Bonus points for clarity, coding standards and quality of comments.
// Bonus points for efficiency of the algorithm.
function isPrime(number) {
if (number < 2) {
return false; // number 1 or lower cannot be a prime number
} else {
for (var i = 2; i < number; i++) { // loop through numbers from 2 to number and check the modulo
if (number % i == 0) {
return false;
}
}
return true;
}
}
function getPrimesBetween(min, max) {
var result = []; // result array that will return the prime numbers
for (var i = min + 1; i < max; i++) { // as it is a between function the min itself should not be checked
if (isPrime(i)) {
result.push(i); // push prime into result array
}
}
return result; // return full array of prime numbers between min and max
}
// some test:
function testIsPrime() {
var result = [];
result.push(isPrime(0) == false);
result.push(isPrime(1) == false);
result.push(isPrime(2) == true);
result.push(isPrime(3) == true);
result.push(isPrime(4) == false);
result.push(isPrime(5) == true);
result.push(isPrime(6) == false);
result.push(isPrime(7) == true);
result.push(isPrime(8) == false);
result.push(isPrime(9) == false);
console.log('testIsPrime: ' + result);
}
function testGetPrimesBetween() {
var result = [];
result.push(getPrimesBetween(0, 25).toString() == [2, 3, 5, 7, 11, 13, 17, 19, 23].toString());
result.push(getPrimesBetween(25, 50).toString() == [29, 31, 37, 41, 43, 47].toString());
result.push(getPrimesBetween(7, 13).toString() == [11].toString()); // edge case where both begin and end numbers are primes
result.push(getPrimesBetween(-2, 1).toString() == [].toString()); // edge case negative minimum and below minimum prime number
console.log('testGetPrimesBetween: ' + result);
}
// end comment:
// I'm aware there is a Sieve (mathematical priciple) out there to make it work more efficiently but I couldn't
// come up with the algoritm by head within 10 minutes. I took the relative bute force approach of just iterating
// through the numbers and iterate again for the primes.
// and to play around and see it work; the JSFiddle: http://jsfiddle.net/yopefonic/LWKnT/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment