diff options
author | Sanjoy Das <sanjoy@google.com> | 2017-11-30 14:26:58 -0800 |
---|---|---|
committer | TensorFlower Gardener <gardener@tensorflow.org> | 2017-11-30 14:30:23 -0800 |
commit | 6bfc73a0b3c6810725a5eb0020470457cc5cc23e (patch) | |
tree | bbd11451f4c7ac5ae4ffa8233e6a2ffaa541d0a8 /tensorflow/core/lib/math | |
parent | 6ebb6d6465ddf2380430de7aa287676e9440df7e (diff) |
Extract out a MathUtil::GCD helper
This fixes a TODO.
PiperOrigin-RevId: 177508258
Diffstat (limited to 'tensorflow/core/lib/math')
-rw-r--r-- | tensorflow/core/lib/math/math_util.h | 17 | ||||
-rw-r--r-- | tensorflow/core/lib/math/math_util_test.cc | 29 |
2 files changed, 46 insertions, 0 deletions
diff --git a/tensorflow/core/lib/math/math_util.h b/tensorflow/core/lib/math/math_util.h index 6f279865e7..9e71598622 100644 --- a/tensorflow/core/lib/math/math_util.h +++ b/tensorflow/core/lib/math/math_util.h @@ -16,6 +16,8 @@ limitations under the License. #ifndef TENSORFLOW_LIB_MATH_MATH_UTIL_H_ #define TENSORFLOW_LIB_MATH_MATH_UTIL_H_ +#include <type_traits> + #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" @@ -59,6 +61,9 @@ class MathUtil { template <typename IntegralType, bool ceil> static IntegralType CeilOrFloorOfRatio(IntegralType numerator, IntegralType denominator); + + template <typename IntegralType> + static IntegralType GCD(IntegralType x, IntegralType y); }; // ---- CeilOrFloorOfRatio ---- @@ -107,6 +112,18 @@ IntegralType MathUtil::CeilOrFloorOfRatio(IntegralType numerator, } } +template <typename IntegralType> +IntegralType MathUtil::GCD(IntegralType a, IntegralType b) { + static_assert(std::is_unsigned<IntegralType>::value, + "signed GCD not supported!"); + while (b != 0) { + IntegralType r = a % b; + a = b; + b = r; + } + return a; +} + } // namespace tensorflow #endif // TENSORFLOW_LIB_MATH_MATH_UTIL_H_ diff --git a/tensorflow/core/lib/math/math_util_test.cc b/tensorflow/core/lib/math/math_util_test.cc index eaf8c31a43..a96e5467c3 100644 --- a/tensorflow/core/lib/math/math_util_test.cc +++ b/tensorflow/core/lib/math/math_util_test.cc @@ -195,4 +195,33 @@ TEST(MathUtil, CeilOfRatio) { #endif } +struct GCDTestCase { + unsigned int x; + unsigned int y; + unsigned int gcd; +}; + +TEST(MathUtil, GCD) { + std::vector<GCDTestCase> testcases({ + {10, 20, 10}, // + {27, 8, 1}, // + {4, 3, 1}, // + {6, 8, 2}, // + {5, 0, 5}, // + {5, 5, 5}, // + {0, 0, 0} // + }); + + for (const auto& tc : testcases) { + EXPECT_EQ(tc.gcd, MathUtil::GCD<uint32>(tc.x, tc.y)); + EXPECT_EQ(tc.gcd, MathUtil::GCD<uint32>(tc.y, tc.x)); + EXPECT_EQ(tc.gcd, MathUtil::GCD<uint64>(tc.x, tc.y)); + EXPECT_EQ(tc.gcd, MathUtil::GCD<uint64>(tc.y, tc.x)); + } + + const uint64 biggish_prime = 1666666667; + EXPECT_EQ(biggish_prime, + MathUtil::GCD<uint64>(biggish_prime * 3, biggish_prime * 4)); +} + } // namespace tensorflow |