1

In a given array of input x can you find all the prime numbers smaller than x? This can be done with a for loop and I provided my code below. However, I'm really interested in knowing if this can be done without a for loop. Was thinking of a possible way using the filter method?

My for loop code

function findThePrimes(num) {
  let nonPrimes  = [], i, j, primes = [];
  for (i = 2; i <= num; ++i) {
    if (!nonPrimes [i]) {
      primes.push(i);
      for (j = i << 1; j <= num; j += i) {
        nonPrimes[j] = true;
      }
    }
  }
  return primes;
}
console.log(findThePrimes(100))

Looking for something similar to the code below

function findThePrimes(num) {
  numArr = Array.from({length: num}, (v, k) => k+1)
  const primeNum = []
  const takeOutPrimes = numArr.filter(num => ...not sure what to do next that will push prime numbers into the primeNum array)
}
console.log(findThePrimes(ANY_NUMBER))
VLAZ
  • 26,331
  • 9
  • 49
  • 67
steelyphil
  • 91
  • 1
  • 1
  • 7
  • For any prime number, your `filter()` predicate should return `true`. Any iteration that doesn't return `true` will be excluded from the result. – Tyler Roper Jun 13 '19 at 14:30
  • Possible duplicate of [How to find prime numbers between 0 - 100?](https://stackoverflow.com/questions/11966520/how-to-find-prime-numbers-between-0-100) – VLAZ Jun 13 '19 at 14:31
  • Also relevant: https://stackoverflow.com/questions/40200089/number-prime-test-in-javascript – VLAZ Jun 13 '19 at 14:31
  • [Here](https://stackoverflow.com/a/37634827/2026606) is a specific answer from VLAZ's first duplicate that uses `.filter()`, granted it uses multiple nested iterations (`map()`, `every()`) which may not be necessary. – Tyler Roper Jun 13 '19 at 14:32
  • 1
    Actually your second example is also a `loop`... – vaku Jun 13 '19 at 14:32
  • 2
    @vaku He didn't say *"without loops"*, he said *"without **for** loops"* :) – Tyler Roper Jun 13 '19 at 14:33
  • All for loops can be written as while loops. – junvar Jun 13 '19 at 14:44
  • @TylerRoper I checked the code and I'm not sure why it doesnt put the number 2 in the array? – steelyphil Jun 13 '19 at 14:45
  • @TylerRoper I set an if conditional at the bottom before returning ```if (n > 2) { primeArr.unshift(2) }``` – steelyphil Jun 13 '19 at 15:07

1 Answers1

0

@TylerRoper gave me a link to a code that was close but the only thing that was missing was 2 in the prime array. So I set a conditional to allow for 2.

Can this be cleaner????

const isPrime = n => Array(Math.ceil(Math.sqrt(n)+1)).fill().map((e,i)=>i).slice(2).every(m => n%m);
const primeArr = Array(n).fill().map((e,i)=>i+1).slice(1).filter(isPrime)
if (n >= 2) {
  primeArr.unshift(2)
}
return primeArr
}
console.log(findPrime(1000).length);```
steelyphil
  • 91
  • 1
  • 1
  • 7