Project Euler #7: 10001st prime

  • + 0 comments

    Solution in JavaScript:

    Create array of 10001 primes once before starting the loop, then get N from array's index

    /////////////// ignore above this line ////////////////////
    
    function main() {
      var t = parseInt(readLine());
      let primesArr = []
      let i = 2
      while (primesArr.length <= 10000) {
        if (isPrime(i) && !primesArr.includes(i)) primesArr.push(i)
        if (Number(primesArr.length) <= 10000) i++
        else break
      }
      for (var a0 = 0; a0 < t; a0++) {
        var n = parseInt(readLine());
            console.log(primesArr[Math.floor(n)-1])
      }
    }
    function isPrime(n) {
      if (n < 2) return false
      let sqrt = Math.floor(Math.sqrt(n))
      for (let i = 2; i <= sqrt; i++) {
        if (n % i == 0) return false
      }
      return true
    }