Decoded: OpenTTD (2003) v1.8 (2018) Source file: math_func.cpp Line-by-line code walkthrough by MaiZure math_func.cpp defines several integer math function approximations Original code: https://github.com/MaiZure/OpenTTD-1.8/blob/master/src/core/math_func.cpp 1 COMMENT (*) 2 BLANK (-) 3 * 4 * 5 * 6 * 7 * 8 * 9 - 10 * 11 - 12 Include the OpenTTD platform-dependent header 13 Include the OpenTTD math function header 14 - 15 Include the OpenTTD safeguard header 16 - 17 * 18 * 19 * 20 * 21 * 22 * 23 * 24 * 25 * 26 Defines LeastCommonMultiple for two integers 27 BLOCK START - LeastCommonMultiple, two input LCM computation 28 If both inputs are zero, then zero is the only LCM 29 If one input is one or both are the same, then the only answer is the non-one 30 If one input is one, then the answer must be the other 31 - 32 Return the product of both inputs divded by the GCD 33 BLOCK END- LeastCommonMultiple 34 * 35 * 36 * 37 * 38 * 39 * 40 * 41 Defines GreatestCommonDivisor for two integers 42 BLOCK START - GreatestCommonDivisor, GCD a la Euclid 43 Loop while the second input has value 44 Store the second input as a temporary value 45 Update b with the modulus a mod b 46 Swap the old b to a 47 Loop until b has no value 48 Return the solution in a 49 - 50 BLOCK END - GreatestCommonDivisor 51 - 52 * 53 * 54 * 55 * 56 * 57 * 58 * 59 Defines DivideApprox with a dividend and a divisor 60 BLOCK START - DivideApprox, integer results that may be off by one 61 Initializes a 'random' number using the input 62 - 63 Calculates the remainder 64 - 65 Computers the integer answer 66 If the random number is less than the remainder (likely for large remainders) 67 Offset the answer by one in another 'random' direction 68 End check for offset 69 - 70 Return the answer that won't always be a simple truncation 71 BLOCK END - DivideApprox 72 - 73 * 74 * 75 * 76 * 77 * 78 * 79 Defines IntSqrt with one argument, the number to root 80 BLOCK START - IntSqrt 81 Initialize the result to 0 82 Compute a number with only the 31st bit high 83 * 84 * 85 Divide the base number of 4 until it is smaller than the input 86 - 87 While the base number is not zero...(gradually refine precision) 88 If the input is larger than the result... 89 Redeuce the result by the base number 90 Halve the result and add back the base number 91 Otherwise we've overshot the result.. 92 Halve the result 93 End check for input number size 94 Cut the base number by another quarter 95 Repeat loop until the base number is zero 96 - 97 * 98 Add one is the input is larger (likely) 99 - 100 Return the result 101 BLOCK END - IntSqrt