[libcxx-commits] [libcxx] [libc++] Implement std::gcd using the binary version (PR #77747)

via libcxx-commits libcxx-commits at lists.llvm.org
Fri Jan 12 02:48:57 PST 2024


================
@@ -48,6 +49,68 @@ constexpr bool test0(int in1, int in2, int out)
     return true;
 }
 
+template <typename T>
+T basic_gcd_(T m, T n) {
+  return n == 0 ? m : basic_gcd_<T>(n, m % n);
+}
+
+template <typename T>
+T basic_gcd(T m, T n) {
+  using Tp = std::make_unsigned_t<T>;
+  if (m < 0 && m != std::numeric_limits<T>::min())
+    m = -m;
+  if (n < 0 && n != std::numeric_limits<T>::min())
+    n = -n;
+  return basic_gcd_(static_cast<Tp>(m), static_cast<Tp>(n));
+}
+
+template <typename Input>
+void do_fuzzy_tests() {
+  std::mt19937 gen(1938);
+  std::uniform_int_distribution<Input> distrib;
+
+  constexpr int nb_rounds = 10000;
+  for (int i = 0; i < nb_rounds; ++i) {
+    Input n = distrib(gen);
+    Input m = distrib(gen);
+    assert(std::gcd(n, m) == basic_gcd(n, m));
+  }
+}
+
+template <typename Input>
+void do_limit_tests() {
+  Input inputs[] = {
+      std::numeric_limits<Input>::min(),
+      std::numeric_limits<Input>::max(),
----------------
AdvenamTacet wrote:

```suggestion
      std::numeric_limits<Input>::min(),
      std::numeric_limits<Input>::min() + 1,
      std::numeric_limits<Input>::min() + 2,
      std::numeric_limits<Input>::max(),
      std::numeric_limits<Input>::max() - 1,
      std::numeric_limits<Input>::max() - 2,
```

https://github.com/llvm/llvm-project/pull/77747


More information about the libcxx-commits mailing list