(svn r27950) -Merge: Documentation updates from 1.7 branch
[openttd.git] / src / core / math_func.cpp
blobd92770208361b8a9d7695f8f4beb7a263beb40ec
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file math_func.cpp Math functions. */
12 #include "../stdafx.h"
13 #include "math_func.hpp"
15 #include "../safeguards.h"
17 /**
18 * Compute least common multiple (lcm) of arguments \a a and \a b, the smallest
19 * integer value that is a multiple of both \a a and \a b.
20 * @param a First number.
21 * @param b second number.
22 * @return Least common multiple of values \a a and \a b.
24 * @note This function only works for non-negative values of \a a and \a b.
26 int LeastCommonMultiple(int a, int b)
28 if (a == 0 || b == 0) return 0; // By definition.
29 if (a == 1 || a == b) return b;
30 if (b == 1) return a;
32 return a * b / GreatestCommonDivisor(a, b);
35 /**
36 * Compute greatest common divisor (gcd) of \a a and \a b.
37 * @param a First number.
38 * @param b second number.
39 * @return Greatest common divisor of \a a and \a b.
41 int GreatestCommonDivisor(int a, int b)
43 while (b != 0) {
44 int t = b;
45 b = a % b;
46 a = t;
48 return a;
52 /**
53 * Deterministic approximate division.
54 * Cancels out division errors stemming from the integer nature of the division over multiple runs.
55 * @param a Dividend.
56 * @param b Divisor.
57 * @return a/b or (a/b)+1.
59 int DivideApprox(int a, int b)
61 int random_like = ((a + b) * (a - b)) % b;
63 int remainder = a % b;
65 int ret = a / b;
66 if (abs(random_like) < abs(remainder)) {
67 ret += ((a < 0) ^ (b < 0)) ? -1 : 1;
70 return ret;
73 /**
74 * Compute the integer square root.
75 * @param num Radicand.
76 * @return Rounded integer square root.
77 * @note Algorithm taken from http://en.wikipedia.org/wiki/Methods_of_computing_square_roots
79 uint32 IntSqrt(uint32 num)
81 uint32 res = 0;
82 uint32 bit = 1UL << 30; // Second to top bit number.
84 /* 'bit' starts at the highest power of four <= the argument. */
85 while (bit > num) bit >>= 2;
87 while (bit != 0) {
88 if (num >= res + bit) {
89 num -= res + bit;
90 res = (res >> 1) + bit;
91 } else {
92 res >>= 1;
94 bit >>= 2;
97 /* Arithmetic rounding to nearest integer. */
98 if (num > res) res++;
100 return res;