Most efficient code for the first 10000 prime numbers?

前端 未结 30 1407
日久生厌
日久生厌 2020-11-29 19:09

I want to print the first 10000 prime numbers. Can anyone give me the most efficient code for this? Clarifications:

  1. It does not matter if your code is ineffici
30条回答
  •  渐次进展
    2020-11-29 19:28

    Using the Array.prototype.find() method in Javascript. 2214.486 ms

    function isPrime (number) {
    
      function prime(element) {
        let start = 2;
        while (start <= Math.sqrt(element)) {
          if (element % start++ < 1) {
            return false;
          }
        }
        return element > 1;
      }
    
      return [number].find(prime)
    
    }
    
    function logPrimes (n) {
    
      let count = 0
      let nth = n
    
      let i = 0
      while (count < nth) {
        if (isPrime(i)) {
          count++
          console.log('i', i) //NOTE: If this line is ommited time to find 10,000th prime is 121.157ms
          if (count === nth) {
            console.log('while i', i)
            console.log('count', count)
          }
        }
        i++
      }
    
    }
    
    console.time(logPrimes)
    
    logPrimes(10000)
    
    console.timeEnd(logPrimes) // 2214.486ms
    

提交回复
热议问题