Implementation of square root Computing Algorithm in Linux kernel using C language
The square root calculation is also implemented in the Linux kernel, just like the sqrt function in the math. h mathematical library.
Square root formula definition:
If a non-negative number
XThe square of is equal
A, That is, the non-negative number
XCalled
AThe square root of arithmetic.
AThe square root of the arithmetic is recorded as the "root number ".
A",
AIt is called radicand ). Calculate a non-negative number
AThe square root operation is called Square. Conclusion: The larger the square number is, the larger the square root of the corresponding Arithmetic (for all positive numbers ). If a positive number has a square root, there must be two, which are opposite to each other. Obviously, if we know one of the two square root values, we can get another square root of the two values in a timely manner based on the concept of the opposite number. Haha, the pupils understand it. If you don't explain it or not, let's look at the Code directly: The same, get the code from the kernel:
#include
#ifdef CONFIG_64BIT#define BITS_PER_LONG 64#else#define BITS_PER_LONG 32#endif/** * int_sqrt - rough approximation to sqrt * @x: integer of which to calculate the sqrt * * A very rough approximation to the sqrt() function. */unsigned long int_sqrt(unsigned long x){unsigned long op, res, one;op = x;res = 0;one = 1UL << (BITS_PER_LONG - 2);while (one > op)one >>= 2;while (one != 0) {if (op >= res + one) {op = op - (res + one);res = res + 2 * one;}res /= 2;one /= 4;}return res;}int main(void){printf("%d\n",int_sqrt(16));return 0 ;}
Running result: