I was just looking at some algorithms for prime numbers and came across this:
for(int i=2;i*i <= n;i++)
{/*assume no operations here*/}
I was just wondering if the above loop will be faster than the following or not?
int x=sqrt(n);
for(int i=2;i<=x;i++)
{/*nop*/}
It depends on the value of
n, of course. Anyway,sqrt()is not guaranteed to give you the right result: due to rounding reasons, you might end up with a value ofxwhich is one less than expected and ruin the algorithm. Rather than going for a micro-optimisation, I would stick to correctness here and use the original version, which is guaranteed to give correct results.