Implementation of square root Computing Algorithm in Linux kernel using C language

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.