summaryrefslogtreecommitdiff
path: root/src/core/math_func.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/math_func.cpp')
-rw-r--r--src/core/math_func.cpp30
1 files changed, 30 insertions, 0 deletions
diff --git a/src/core/math_func.cpp b/src/core/math_func.cpp
index 7f0630a97..2b8ca3309 100644
--- a/src/core/math_func.cpp
+++ b/src/core/math_func.cpp
@@ -46,3 +46,33 @@ int GreatestCommonDivisor(int a, int b)
return a;
}
+
+/**
+ * Compute the integer square root.
+ * @param num Radicand.
+ * @return Rounded integer square root.
+ * @note Algorithm taken from http://en.wikipedia.org/wiki/Methods_of_computing_square_roots
+ */
+uint32 IntSqrt(uint32 num)
+{
+ uint32 res = 0;
+ uint32 bit = 1UL << 30; // Second to top bit number.
+
+ /* 'bit' starts at the highest power of four <= the argument. */
+ while (bit > num) bit >>= 2;
+
+ while (bit != 0) {
+ if (num >= res + bit) {
+ num -= res + bit;
+ res = (res >> 1) + bit;
+ } else {
+ res >>= 1;
+ }
+ bit >>= 2;
+ }
+
+ /* Arithmetic rounding to nearest integer. */
+ if (num > res) res++;
+
+ return res;
+}