summaryrefslogtreecommitdiff
path: root/src/core
diff options
context:
space:
mode:
authormichi_cc <michi_cc@openttd.org>2011-12-03 23:40:46 +0000
committermichi_cc <michi_cc@openttd.org>2011-12-03 23:40:46 +0000
commitd3b7b89493e025654d218fb77da095649b4f6ba2 (patch)
tree6667e4164c5c8bda4c1b7092376872b315c65610 /src/core
parentf98312eb77e12cfa45de40a1b4e8359160b0d9ff (diff)
downloadopenttd-d3b7b89493e025654d218fb77da095649b4f6ba2.tar.xz
(svn r23415) -Feature: Infrastructure maintenance costs.
Diffstat (limited to 'src/core')
-rw-r--r--src/core/math_func.cpp30
-rw-r--r--src/core/math_func.hpp2
2 files changed, 32 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;
+}
diff --git a/src/core/math_func.hpp b/src/core/math_func.hpp
index 19f2f53d6..92893ed31 100644
--- a/src/core/math_func.hpp
+++ b/src/core/math_func.hpp
@@ -346,4 +346,6 @@ static FORCEINLINE int RoundDivSU(int a, uint b)
}
}
+uint32 IntSqrt(uint32 num);
+
#endif /* MATH_FUNC_HPP */