Suppose for a given integer N, I need to run a loop square root of N times.
In C++, I can do it in these two ways like-
1)
long long sqrtN = std::sqrt(N);
for (long long i=1; i < sqrtN; i++) {
// some piece of code
}
for (long long i=1; i * i < N; i++) {
// some same piece of code
}
I found that std::sqrt() has O(logn) complexity. Also, I believe the multiplication of numbers is just a constant time operation.
So, it feels that the 2nd version is faster. But, for a very large value of n, that constant time in 2nd version may be significant.
Thus, I am not really sure which way is more efficient?