int_sqrt.c 712 B

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