| rozick1 (64) | |||
My implementation was this:
The problem with this is that you have to start guessing how many numbers you'll need in the vector (I'm assuming that there isn't a formula for what number the nth prime is?). You also start using lots of RAM. Is there a way of avoiding these problems? | |||
|
Last edited on
|
|||
| Veltas (336) | |
|
If you want a specific prime then you should use a direct approach like trial division. http://en.wikipedia.org/wiki/Prime#Trial_division A prime sieve is the fastest way of generating all the primes in a range. The memory complexity is a real issue (how much memory you need to find a certain number of primes) but it can be seriously reduced by only creating smaller arrays (or vectors) of integers before sieving from them and discarding these smaller arrays before moving onto the next sub-range. Before even doing this, however, immediately I could suggest that you: 1. Don't bother initialising each element of primesarr in a loop; use the 2. Use a bool, not an int, to store primesarr's elements. Use true and false rather than 1 and 0.3. You only need to go up to sqrt(primesupto) in your main for loop to cover all primes in that range. | |
|
|
|