Let's say I have an integer n
and I want to find the largest number m
for which the square of that number is smaller than n
.
What would be the optimal solution for this problem?
Let's say I have an integer n
and I want to find the largest number m
for which the square of that number is smaller than n
.
What would be the optimal solution for this problem?
"The Optimal Solution" rarely exists, but a reasonably fast algorithm is as follows (anyone knows its name?), it's called the Babylonian Method:
int num = 4567;
int r1 = num / 2;
int r2 = 2;
while (std::abs(r2 - r1) > 1) {
r2 = (r1 + r2) / 2;
r1 = num / r2;
}
Here r1
and r2
are the lower and higher approximations of the square root. In your case, you'll need the smaller one.
Since you're just looking for the integer part, you could do it this way:
int n = 123; //or whatever you want
int m = 1;
while (m * m <= n) {
m = m + 1;
}
return (m - 1);