Asa's CP Library

a01sa01to's competitive programming library. Requires C++20 or higher with GCC. This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub a01sa01to/cp-library

:heavy_check_mark: ポラード・ロー素因数分解法
(library/math/pollards-rho.hpp)

大きな素因数を確率的に探す乱択アルゴリズム。

ベースはフロイドの循環検出法と誕生日のパラドックス。

$n$ に素因数 $p$ があるとき、 $x \bmod n, y \bmod n$ が $\bmod p$ で一致するなら、 $\vert x - y \vert$ は $p$ の倍数であるので、 $\gcd(\vert x - y \vert, n)$ は $n$ の素因数の候補となる。 よって、以下のアルゴリズムを用いればよさそう。

  1. $x = 2, y = 2, d = 1$ とする。
  2. $d = 1$ である限り、
    1. $x = f(x), y = f^2(y)$ とする。
    2. $d = \gcd(\vert x - y \vert, n)$ とする。
  3. $d = n$ ならば、失敗。 どうでなければ $d$ は $n$ の素因数の候補である。

これを繰り返していけばよさそう。

$n$ 素数の場合は常に失敗するので、先に素数判定をしておくべき。 合成数でも失敗するが、 $x, y$ の初期値は seed とみなせる? ので $x, y$ を変えて繰り返すことで成功する確率を上げられる。 $f$ は擬似乱数生成器、 $f(x) = (x^2 + 1) \bmod n$ など。

計算量は $O(n^{1/4} \text{polylog}(n))$ らしいが、厳密には求まってないらしい。

Depends on

Verified with

Code

#pragma once

#include <algorithm>
#include <cassert>
#include <concepts>
#include <functional>
#include <numeric>
#include <utility>
#include <vector>
using namespace std;

#include "./miller-rabin.hpp"

namespace asalib::math {
  template<integral T>
  constexpr vector<pair<T, T>> pollards_rho(T n) {
    if (n < 2) [[unlikely]]
      return {};

    vector<pair<T, T>> res(0);
    // ある程度小さい素因数については前もって素因数分解しておく
    for (T i = 2; i * i <= min(static_cast<T>(10000), n); ++i) {
      if (n % i == 0) {
        T e = 0;
        while (n % i == 0) n /= i, ++e;
        res.emplace_back(i, e);
      }
    }
    if (n == 1) [[unlikely]]
      return res;

    // ここからメイン
    static_assert(sizeof(T) == 4 || sizeof(T) == 8, "T must be 32-bit or 64-bit integer type");
    constexpr bool is_64bit = sizeof(T) == 8;
    auto f = [&](T x, T s) -> T {
      if constexpr (is_64bit)
        return (static_cast<__uint128_t>(x) * x + s) % n;
      else
        return (static_cast<unsigned long long>(x) * x + s) % n;
    };
    function<void(T&, T)> rho = [&](T& num, T cnt) {
      if (num == 1) [[unlikely]]
        return;
      if (miller_rabin_test(num)) {
        res.emplace_back(num, cnt);
        num = 1;
        return;
      }
      T s = 0;
      while (true) {
        T x = ++s, y = f(x, s);
        while (true) {
          T p = gcd(y - x + num, num);
          if (p == 0 || p == num) break;  // 失敗、 seed 変えてやり直し
          if (p != 1) {
            assert(num % p == 0);
            T e = 0;
            while (num % p == 0) num /= p, ++e;
            rho(p, cnt * e);
            if (num > 1) rho(num, cnt);
            return;
          }
          x = f(x, s), y = f(f(y, s), s);
        }
      }
    };
    while (n > 1) rho(n, 1);

    sort(res.begin(), res.end());
    return res;
  }
}  // namespace asalib::math
#line 2 "library/math/pollards-rho.hpp"

#include <algorithm>
#include <cassert>
#include <concepts>
#include <functional>
#include <numeric>
#include <utility>
#include <vector>
using namespace std;

#line 2 "library/math/miller-rabin.hpp"

#line 7 "library/math/miller-rabin.hpp"
using namespace std;

#line 2 "library/_internal/math/modpow.hpp"

#line 4 "library/_internal/math/modpow.hpp"
using namespace std;

namespace asalib::_internal::math {
  template<integral T>
  T modpow(T a, T n, T mod) {
    static_assert(sizeof(T) == 4 || sizeof(T) == 8, "T must be 32-bit or 64-bit integer type");
    constexpr bool is_64bit = sizeof(T) == 8;

    T res = 1;
    while (n) {
      if constexpr (is_64bit) {
        if (n & 1) res = static_cast<__uint128_t>(res) * a % mod;
        a = static_cast<__uint128_t>(a) * a % mod;
      }
      else {
        if (n & 1) res = static_cast<unsigned long long>(res) * a % mod;
        a = static_cast<unsigned long long>(a) * a % mod;
      }
      n >>= 1;
    }
    return res;
  }
}  // namespace asalib::_internal::math
#line 10 "library/math/miller-rabin.hpp"

namespace asalib::math {
  template<integral T>
  constexpr bool miller_rabin_test(T n) {
    if (n < 2) [[unlikely]]
      return false;
    if (n % 2 == 0) return n == 2;
    T d = n - 1, s = 0;
    while (d % 2 == 0) d >>= 1, ++s;
    assert(d % 2 == 1);

    static_assert(sizeof(T) == 4 || sizeof(T) == 8, "T must be 32-bit or 64-bit integer type");
    constexpr bool is_64bit = sizeof(T) == 8;

    function<bool(T)> test = [&](T a) {
      T x = _internal::math::modpow(a, d, n);
      if (x == 0) [[unlikely]]
        return false;
      if (x == 1) [[unlikely]]
        return true;
      for (T _ = 0; _ < s; ++_) {
        T y;
        if constexpr (is_64bit)
          y = static_cast<__uint128_t>(x) * x % n;
        else
          y = static_cast<unsigned long long>(x) * x % n;
        if (y == 1 && x != 1 && x != n - 1) return false;
        x = y;
      }
      return x == 1;
    };

    function<bool(vector<T>)> tests = [&](vector<T> basis) {
      for (T a : basis)
        if (!test(a)) return false;
      return true;
    };

    if (n < 2'047) return test(2);
    if (n < 1'373'653) return tests({ 2, 3 });
    if (n < 9'080'191) return tests({ 31, 73 });
    if (n < 25'326'001) return tests({ 2, 3, 5 });
    if (n < 3'215'031'751) return tests({ 2, 3, 5, 7 });
    if (n < 4'759'123'141) return tests({ 2, 7, 61 });
    if (n < 1'122'004'669'633) return tests({ 2, 13, 23, 1662803 });
    if (n < 2'152'302'898'747) return tests({ 2, 3, 5, 7, 11 });
    if (n < 3'474'749'660'383) return tests({ 2, 3, 5, 7, 11, 13 });
    if (n < 341'550'071'728'321) return tests({ 2, 3, 5, 7, 11, 13, 17 });
    if (n < 3'825'123'056'546'413'051) return tests({ 2, 3, 5, 7, 11, 13, 17, 19, 23 });
    if (static_cast<ull>(n) <= 18'446'744'073'709'551'615ULL) return tests({ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 });
    // 18'446'744'073'709'551'616 は 2^64 であり、これ以上の数は 64 ビット整数型では表現できない
    // TODO: 多倍長整数を使う場合は if を追加する
    // TODO: C++23 以降なら __builtin_unreachable() -> std::unreachable() に変更可能
    __builtin_unreachable();
  }
}  // namespace asalib::math
#line 13 "library/math/pollards-rho.hpp"

namespace asalib::math {
  template<integral T>
  constexpr vector<pair<T, T>> pollards_rho(T n) {
    if (n < 2) [[unlikely]]
      return {};

    vector<pair<T, T>> res(0);
    // ある程度小さい素因数については前もって素因数分解しておく
    for (T i = 2; i * i <= min(static_cast<T>(10000), n); ++i) {
      if (n % i == 0) {
        T e = 0;
        while (n % i == 0) n /= i, ++e;
        res.emplace_back(i, e);
      }
    }
    if (n == 1) [[unlikely]]
      return res;

    // ここからメイン
    static_assert(sizeof(T) == 4 || sizeof(T) == 8, "T must be 32-bit or 64-bit integer type");
    constexpr bool is_64bit = sizeof(T) == 8;
    auto f = [&](T x, T s) -> T {
      if constexpr (is_64bit)
        return (static_cast<__uint128_t>(x) * x + s) % n;
      else
        return (static_cast<unsigned long long>(x) * x + s) % n;
    };
    function<void(T&, T)> rho = [&](T& num, T cnt) {
      if (num == 1) [[unlikely]]
        return;
      if (miller_rabin_test(num)) {
        res.emplace_back(num, cnt);
        num = 1;
        return;
      }
      T s = 0;
      while (true) {
        T x = ++s, y = f(x, s);
        while (true) {
          T p = gcd(y - x + num, num);
          if (p == 0 || p == num) break;  // 失敗、 seed 変えてやり直し
          if (p != 1) {
            assert(num % p == 0);
            T e = 0;
            while (num % p == 0) num /= p, ++e;
            rho(p, cnt * e);
            if (num > 1) rho(num, cnt);
            return;
          }
          x = f(x, s), y = f(f(y, s), s);
        }
      }
    };
    while (n > 1) rho(n, 1);

    sort(res.begin(), res.end());
    return res;
  }
}  // namespace asalib::math
Back to top page