Question:
How can you calculate the square root without using sqrt(n)
and n^0.5
?
Answer:
The question actually has many solutions.
The most banal is the method of half division.
double l = 0;
double r = 1e100; //большое число
double m;
while (r - l > 1e-8){ //точность
m = l + (r - l)/2;
if (m*m > n) l = m;
else r = m;
}
//ответ в l
There are more original ways, for example, simulating a calculation in a column (here is an example , I will not give the code)
The method is more for C, but I think it can be used in Java as well. Explanation
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1 итерация
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2 итерация, можно удалить
return 1/y;
}
You can use logarithms
return Math.exp( Math.log(n) / 2);
You can use numerical methods, such as Newton's method
double x = 1;
for (;;) {
double nx = (x + n / x) / 2;
if (abs (x - nx) < 1e-10) break; //точность
x = nx;
}
There are many other ways, it all depends on the specific requirements.