int_sqrt.c 652 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*
  2. * Copyright (C) 2013 Davidlohr Bueso <davidlohr.bueso@hp.com>
  3. *
  4. * Based on the shift-and-subtract algorithm for computing integer
  5. * square root from Guy L. Steele.
  6. */
  7. #include <linux/kernel.h>
  8. #include <linux/export.h>
  9. /**
  10. * int_sqrt - rough approximation to sqrt
  11. * @x: integer of which to calculate the sqrt
  12. *
  13. * A very rough approximation to the sqrt() function.
  14. */
  15. unsigned long int_sqrt(unsigned long x)
  16. {
  17. unsigned long b, m, y = 0;
  18. if (x <= 1)
  19. return x;
  20. m = 1UL << (BITS_PER_LONG - 2);
  21. while (m != 0) {
  22. b = y + m;
  23. y >>= 1;
  24. if (x >= b) {
  25. x -= b;
  26. y += m;
  27. }
  28. m >>= 2;
  29. }
  30. return y;
  31. }
  32. EXPORT_SYMBOL(int_sqrt);