# Find Prime Numbers in Range

Published: 2017-05-21 11:09:59 +0000
Categories: Javascript,

Javascript

### Description

Will find and identify any prime numbers between the given start and end values. Primes are identified using a factorial.

Originally written as part of a solution for my May 2016 puzzle. The original solution was written in Python, this snippet is part of a (successful) attempt to rewrite that in javascript so that the solution can simply be dropped into the Developer Tools console to solve the puzzle in browser.

### Snippet

``````// Calculate all primes between a lower and upper bound
function calculatePrimesForRange(l,h){
var primes=[];
for (i=l; i<h; i++){

if (checkNumPrime(i)){
primes.push(i);
}

}
return primes;
}

// Check whether a number is a prime
function checkNumPrime(n){

// Check whether the number is 1,2 or 3
if (n<4){
return true;
}

// Check the number isn't directly divisible by 2 or 3
if (n%2 == 0 || n%3 == 0){
return false;
}

var di=2;
var i = 5;

// Don't calculcate higher than the square root (rounded down if needed)
var lim = Math.floor(Math.sqrt(n));

while (i < lim){

if (n%i == 0){
return false;
}
i=i+di;
di=6-di;
}

// If we haven't already returned, n is prime
return true;

}

``````

### Usage Example

``````calculatePrimesForRange(1,100);
``````

BSD-3-Clause

### Keywords

Primes, numbers, range, factorial,