Created
June 19, 2015 12:34
-
-
Save StoyanKostov/eea92afb6f830a01450d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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