int_sqrt.c 676 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. #include <linux/bitops.h>
  10. /**
  11. * int_sqrt - rough approximation to sqrt
  12. * @x: integer of which to calculate the sqrt
  13. *
  14. * A very rough approximation to the sqrt() function.
  15. */
  16. unsigned long int_sqrt(unsigned long x)
  17. {
  18. unsigned long b, m, y = 0;
  19. if (x <= 1)
  20. return x;
  21. m = 1UL << (__fls(x) & ~1UL);
  22. while (m != 0) {
  23. b = y + m;
  24. y >>= 1;
  25. if (x >= b) {
  26. x -= b;
  27. y += m;
  28. }
  29. m >>= 2;
  30. }
  31. return y;
  32. }
  33. EXPORT_SYMBOL(int_sqrt);