The std::vector<>
is a dynamically sized container. For the The allocation strategy is implementation dependent, but for sake of the argument, assume the .capacity()
of a std::vector<>
starts off at 1 and doubles each time the vector's size exceeds the current capacity. This capacity increase requires a reallocation of storage, and possibly a copying of the entire array contents to a new location. If you are generating 1 trillion primes, you'll need 40 reallocations and will have done 1 trillion number copies over the course of the 40 reallocations. This is wasting time. If the operating system gets involved with virtual memory paging, you are going to suck up a lot more time.
If you let this loop run over night, or even over a fort-night, will this loop ever end? No! i
will overflow the long long
and become negative, and slowingslowly increment back towards positive numbers and repeat. Forever is not long enough. Use, at the very least, i > 0
as the loop test condition.
A long long
has at least 64 bits. A double
has only a 52 bit mantissa. This means when you pass a large long long
to sqrt( )
, you will end up losing a few bits of precision, which can make your sqrt()
return slightly the wrong value. When you test sqrt(i) <= primes[j]
, if i
is greater than 2^52, and is a perfect square, you might return a value slightly less than the correct value and fail to test the last prime value, and erroneously declare the perfect square a prime number.