In theory the second version is faster because of simpified/removed multiplication. A multiplication is considered to be slower than an addition.
Normally you should evaluate std::sqrt(limit) once before the loop otherwise that costly expression is evaluated for each i. But it is possible that the optimizer realizes that limit is not changed and thus does it for you...
The last valid position in std::vector<bool> primes_bool_array (limit, true); is limit-1;
the loop condition is <= limit.
Once that is fixed, consider this: limit is the square of a prime number and std::sqrt(limit) does not return the precise integer value of its square root.
Ok, so I did what you said, but when I enter a number that is a prime for the parameter of the function, that number does not come as a result. Here is my updated code:
it wouldn't. Its up to 61. Put 62 in to see 61, or make it <=
The sieve isn't as efficient as GCD on the product of all known primes. Its use comes in when you get past the known prime realm, or when the product is too big, both of which hit way out past 61 for sure :)
> with my compiler (g++) this produces
> First failure at i = 94906267 Difference is 5.26779e-009
> However, I bet this is implementation-dependent.
If the floating point environment conforms to he IEEE specification (most do), then the error in the result of std::sqrt() is guaranteed to be less than half ulp.