Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StoyanKostov/eea92afb6f830a01450d to your computer and use it in GitHub Desktop.
Save StoyanKostov/eea92afb6f830a01450d to your computer and use it in GitHub Desktop.
/* Task description */
/*
Write a function that finds all the prime numbers in a range
1) it should return the prime numbers in an array
2) it must throw an Error if any on the range params is not convertible to `Number`
3) it must throw an Error if any of the range params is missing
*/
function findPrimes(from, to) {
if (isNaN(Number(from)) || isNaN(Number(to))) {
throw new Error('At least one param is not convertible to `Number` or not passed');
}
var primesArr = [];
// Exchange range values if nessesary for while loop condition
if (from > to) {
from = from + to;
to = from - to;
from = from - to;
}
while(from <= to){
var prime = isPrime(from);
if (prime) {
primesArr.push(prime);
}
from += 1;
}
return primesArr;
}
function isPrime(num){
if (num <= 1) {
return false;
}else if (num === 2) {
return num;
}
var i,
numSquareRoot = Math.ceil(Math.sqrt(num));
for (i = 2; i <= numSquareRoot; i++) {
if (num % i === 0) {
return false;
}
}
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment