00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 #ifndef OR_TOOLS_BASE_MATHUTIL_H_
00016 #define OR_TOOLS_BASE_MATHUTIL_H_
00017
00018 #include <math.h>
00019 #include <algorithm>
00020 #include <vector>
00021
00022 #include "base/basictypes.h"
00023 #include "base/casts.h"
00024 #include "base/integral_types.h"
00025 #include "base/logging.h"
00026 #include "base/macros.h"
00027
00028 namespace operations_research {
00029 class MathUtil {
00030 public:
00031
00032
00033
00034
00035
00036
00037
00038 template<typename IntegralType>
00039 static IntegralType CeilOfRatio(IntegralType numerator,
00040 IntegralType denominator) {
00041 DCHECK_NE(0, denominator);
00042 const IntegralType rounded_toward_zero = numerator / denominator;
00043 const IntegralType intermediate_product = rounded_toward_zero * denominator;
00044 const bool needs_adjustment = (rounded_toward_zero >= 0) &&
00045 ((denominator > 0 && numerator > intermediate_product) ||
00046 (denominator < 0 && numerator < intermediate_product));
00047 const IntegralType adjustment
00048 = static_cast<IntegralType>(needs_adjustment);
00049 const IntegralType ceil_of_ratio = rounded_toward_zero + adjustment;
00050 return ceil_of_ratio;
00051 }
00052 template<typename IntegralType>
00053 static IntegralType FloorOfRatio(IntegralType numerator,
00054 IntegralType denominator) {
00055 DCHECK_NE(0, denominator);
00056 const IntegralType rounded_toward_zero = numerator / denominator;
00057 const IntegralType intermediate_product = rounded_toward_zero * denominator;
00058 const bool needs_adjustment = (rounded_toward_zero <= 0) &&
00059 ((denominator > 0 && numerator < intermediate_product) ||
00060 (denominator < 0 && numerator > intermediate_product));
00061 const IntegralType adjustment =
00062 static_cast<IntegralType>(needs_adjustment);
00063 const IntegralType floor_of_ratio = rounded_toward_zero - adjustment;
00064 return floor_of_ratio;
00065 }
00066
00067
00068 static unsigned int GCD(unsigned int x, unsigned int y) {
00069 while (y != 0) {
00070 unsigned int r = x % y;
00071 x = y;
00072 y = r;
00073 }
00074 return x;
00075 }
00076
00077
00078
00079 static unsigned int LeastCommonMultiple(unsigned int a, unsigned int b) {
00080 if (a > b) {
00081 return (a / MathUtil::GCD(a, b)) * b;
00082 } else if (a < b) {
00083 return (b / MathUtil::GCD(b, a)) * a;
00084 } else {
00085 return a;
00086 }
00087 }
00088
00089
00090
00091
00092
00093
00094 template<typename T> static T Abs(const T x) {
00095 return x > 0 ? x : -x;
00096 }
00097
00098
00099 template <typename T> static T Square(const T x) {
00100 return x * x;
00101 }
00102 };
00103
00104 }
00105
00106
00107 #endif // OR_TOOLS_BASE_MATHUTIL_H_