Implementación de función SQRT (X);¿Qué es $ (i ^ 2 \ leq x) \ tierra ((I + 1) ^ 2> x) $ Comprobación?
-
29-09-2020 - |
Pregunta
Recientemente estaba trabajando en una pregunta de código de leet
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only
the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
Aquí hay una solución que realmente me gusta y entiendo, excepto por una línea.Está utilizando la búsqueda binaria para llegar a la solución:
int mySqrt(int x) {
if (x == 0) return x;
int left = 1, right = INT_MAX, mid;
while(left < right) {
mid = left + (right - left)/2;
if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
return mid;
}
if (mid < x/mid) {
left = mid + 1;
} else { // mid > x/mid
right = mid;
}
}
return right;
}
La pregunta conceptual es: ¿por qué es cierto que le dan un número particular, por ejemplo, $ i $ , $$ (i ^ 2 \ leq x) \ tierra ((i + 1) ^ 2> x) $$ devuelve si $ i $ es el truncadoRepresentación entera de la raíz cuadrada de $ x $ ?(El bloque de código anterior se devuelve en la condición idéntica, pero la desigualdad se reorganiza para evitar el desbordamiento entero)
Solución
Pondré las dos desigualdades juntas, para la legibilidad: $ i ^ 2 \ leq x <(i + 1) ^ 2 $ .
Tomar el cuadrado positivo de un número positivo es una función monótona.Por eso, $$ i ^ 2 \ leq x <(i + 1) ^ 2 \ implica i \ leq | \ sqrt {x} |
Luego, la parte intervil de $ | \ sqrt {x} | $ es obviamente $ i $ .