diff --git a/snippet-template.md b/snippet-template.md index 63d6665d8..f95eabc3d 100644 --- a/snippet-template.md +++ b/snippet-template.md @@ -8,4 +8,4 @@ Explain briefly how the snippet works. const functionName = arguments => {functionBody} // functionName(sampleInput) -> sampleOutput -``` +``` \ No newline at end of file diff --git a/snippets/primes.md b/snippets/primes.md new file mode 100644 index 000000000..81e8f2999 --- /dev/null +++ b/snippets/primes.md @@ -0,0 +1,16 @@ +### primes + +Generates primes up to a given number, using the Sieve of Eratosthenes. + +Generate an array from `2` to the given number. Use `Array.filter()` to filter out the values divisible by any number from `2` to the square root of the provided number. + +```js +const primes = num => { + let arr = Array.from({length:num-1}).map((x,i)=> i+2), + sqroot = Math.floor(Math.sqrt(num)), + numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=> i+2); + numsTillSqroot.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y==x))); + return arr; +} +// primes(10) -> [2,3,5,7] +```