OpenTTD Source  1.11.0-beta2
math_func.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #include "../stdafx.h"
11 #include "math_func.hpp"
12 
13 #include "../safeguards.h"
14 
24 int LeastCommonMultiple(int a, int b)
25 {
26  if (a == 0 || b == 0) return 0; // By definition.
27  if (a == 1 || a == b) return b;
28  if (b == 1) return a;
29 
30  return a * b / GreatestCommonDivisor(a, b);
31 }
32 
39 int GreatestCommonDivisor(int a, int b)
40 {
41  while (b != 0) {
42  int t = b;
43  b = a % b;
44  a = t;
45  }
46  return a;
47 
48 }
49 
57 int DivideApprox(int a, int b)
58 {
59  int random_like = ((a + b) * (a - b)) % b;
60 
61  int remainder = a % b;
62 
63  int ret = a / b;
64  if (abs(random_like) < abs(remainder)) {
65  ret += ((a < 0) ^ (b < 0)) ? -1 : 1;
66  }
67 
68  return ret;
69 }
70 
77 uint32 IntSqrt(uint32 num)
78 {
79  uint32 res = 0;
80  uint32 bit = 1UL << 30; // Second to top bit number.
81 
82  /* 'bit' starts at the highest power of four <= the argument. */
83  while (bit > num) bit >>= 2;
84 
85  while (bit != 0) {
86  if (num >= res + bit) {
87  num -= res + bit;
88  res = (res >> 1) + bit;
89  } else {
90  res >>= 1;
91  }
92  bit >>= 2;
93  }
94 
95  /* Arithmetic rounding to nearest integer. */
96  if (num > res) res++;
97 
98  return res;
99 }
DivideApprox
int DivideApprox(int a, int b)
Deterministic approximate division.
Definition: math_func.cpp:57
math_func.hpp
IntSqrt
uint32 IntSqrt(uint32 num)
Compute the integer square root.
Definition: math_func.cpp:77
GreatestCommonDivisor
int GreatestCommonDivisor(int a, int b)
Compute greatest common divisor (gcd) of a and b.
Definition: math_func.cpp:39
abs
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:21
LeastCommonMultiple
int LeastCommonMultiple(int a, int b)
Compute least common multiple (lcm) of arguments a and b, the smallest integer value that is a multip...
Definition: math_func.cpp:24