Project Euler Problems 1 to 100 - Problem 7: 10001st prime

Tell us what’s happening:

My code is correct, but it always just times out. When computing on my vs code is works and gives the correct solutions

Your code so far

function nthPrime(n) {
  let array = [0]
  for(let i = 3; i > 0; i++){
    if (array.length > n){break}
    let o = 0
    for (let t=0; t<= array.length-1; t++){
      if (i % array[t] == 0){
        o += 1
      }
    }
    if (o == 0){
      array.push(i)
    }
  }
  let prime = array[array.length-1]
  return prime;
}


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 OPR/109.0.0.0

Challenge Information:

Project Euler Problems 1 to 100 - Problem 7: 10001st prime

Yeah, you need to use a less inefficient approach.

I’d also recommend using meaningful words as variable names.

Edit: This gives you an upper bound for what the nth prime is. With that bound, you can use more classic efficient prime finding algorithms.

1 Like