| Viewed 93 times

How Many "Prime Numbers" in Javascript?


I need a function that finds how many prime numbers there are, up to the given integer.

1 Answer
Mohammad Qandeel
Answered
7
function primeNumbers(num) {
 if(num<0)return 0;
 num=Math.trunc(num);
  let prime =  Array(num+1); 
   prime.fill(true);
   for(let p = 2; p*p <=num; p++) 
        { 
            // If prime[p] is not changed, then it is a prime 
            if(prime[p]) 
            { 
                // Update all multiples of p 
                for(let i = p*p; i <= num; i += p) 
                    prime[i] = false; 
            } 
        } 
    return prime.filter(x=>x).length-2;   
}

Example

primeNumbers(2) //1

primeNumbers(3) //2

primeNumbers(4) //2

primeNumbers(5) //3



Related Questions