proconlib

This documentation is automatically generated by competitive-verifier/competitive-verifier

View the Project on GitHub anqooqie/proconlib

:heavy_check_mark: Extended Lucas' theorem (tools/extended_lucas.hpp)

It precomputes ${}_n C_r \pmod{M}$ for any $n$, any $r$ and a small fixed $M$.

References

License

Author

Constructor

tools::extended_lucas<T> cache();

It precomputes ${}_n \mathrm{C}_r \pmod{M}$ for any $n$ and $r$ where $M$ is T::mod().

Constraints

Time Complexity

fact

M cache.fact(long long n);

It returns $n! \pmod{M}$.

Constraints

Time Complexity

binomial

M cache.binomial(long long n, long long r);

It returns $\dbinom{n}{r} \pmod{M}$. Note that $\dbinom{-n}{r} = (-1)^r \dbinom{n + r - 1}{r}$.

Constraints

Time Complexity

combination

M cache.combination(long long n, long long r);

It returns

\[\begin{align*} \left\{\begin{array}{ll} {}_n \mathrm{C}_r \pmod{M} & \text{(if $0 \leq r \leq n$)}\\ 0 \pmod{M} & \text{(otherwise)} \end{array}\right.& \end{align*}\]

Constraints

Time Complexity

permutation

M cache.permutation(long long n, long long r);

It returns

\[\begin{align*} \left\{\begin{array}{ll} {}_n \mathrm{P}_r \pmod{M} & \text{(if $0 \leq r \leq n$)}\\ 0 \pmod{M} & \text{(otherwise)} \end{array}\right.& \end{align*}\]

Constraints

Time Complexity

combination_with_repetition

M cache.combination_with_repetition(long long n, long long r);

It returns

\[\begin{align*} \left\{\begin{array}{ll} {}_n \mathrm{H}_r \pmod{M} & \text{(if $n \geq 0$ and $r \geq 0$)}\\ 0 \pmod{M} & \text{(otherwise)} \end{array}\right.& \end{align*}\]

Constraints

Time Complexity

Depends on

Required by

Verified with

Code

#ifndef TOOLS_EXTENDED_LUCAS_HPP
#define TOOLS_EXTENDED_LUCAS_HPP

#include <vector>
#include <cassert>
#include <utility>
#include <iterator>
#include "tools/int128_t.hpp"
#include "tools/prime_factorization.hpp"
#include "tools/run_length.hpp"
#include "tools/garner.hpp"

// Source: https://hitonanode.github.io/cplib-cpp/number/combination.hpp.html
// License: MIT
// Author: hitonanode

// MIT License
// 
// Copyright (c) 2019 Ryotaro Sato
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

namespace tools {

  template <class M>
  class extended_lucas {
    struct combination_prime_pow {
      int p, q, m;
      ::std::vector<int> fac, invfac, ppow;

      long long ej(long long n) const {
        long long ret = 0;
        while (n) ret += n, n /= this->p;
        return ret;
      }

      combination_prime_pow(const int p_, const int q_) : p(p_), q(q_), m(1), ppow{1} {
        for (int t = 0; t < this->q; ++t) this->m *= this->p, this->ppow.push_back(this->m);
        this->fac.assign(this->m, 1);
        this->invfac.assign(this->m, 1);
        for (int i = 1; i < this->m; ++i) this->fac[i] = static_cast<long long>(this->fac[i - 1]) * (i % this->p ? i : 1) % this->m;
        this->invfac[this->m - 1] = this->fac[this->m - 1]; // Same as Wilson's theorem
        assert(1LL * this->fac.back() * this->invfac.back() % this->m == 1);
        for (int i = this->m - 1; i; --i) this->invfac[i - 1] = static_cast<long long>(this->invfac[i]) * (i % this->p ? i : 1) % this->m;
      }

      int fact(const long long n) const {
        assert(n >= 0);
        const auto q0 = this->ej(n / this->p);
        return q0 < this->q ? static_cast<long long>(this->fac[n]) * this->ppow[q0] % this->m : 0;
      }

      int combination(long long n, long long r) const {
        assert(0 <= r && r <= n);
        if (this->p == 2 && this->q == 1) return !((~n) & r); // Lucas
        long long k = n - r;
        const long long e0 = this->ej(n / this->p) - this->ej(r / this->p) - this->ej(k / this->p);
        if (e0 >= q) return 0;

        long long ret = this->ppow[e0];
        if (this->q == 1) { // Lucas
          while (n) {
            ret = ::tools::int128_t(ret) * this->fac[n % this->p] * this->invfac[r % this->p] * this->invfac[k % this->p] % this->p;
            n /= this->p, r /= this->p, k /= this->p;
          }
          return static_cast<int>(ret);
        } else {
          if ((p > 2 || q < 3) && (this->ej(n / this->m) - this->ej(r / this->m) - this->ej(k / this->m)) & 1) ret = this->m - ret;
          while (n) {
            ret = ::tools::int128_t(ret) * this->fac[n % this->m] * this->invfac[r % this->m] * this->invfac[k % this->m] % this->m;
            n /= this->p, r /= this->p, k /= this->p;
          }
          return static_cast<int>(ret);
        }
      }
    };

    ::std::vector<combination_prime_pow> m_cpps;

  public:
    extended_lucas() {
      const auto prime_factors = ::tools::prime_factorization(M::mod());
      ::std::vector<::std::pair<int, int>> distinct_prime_factors;
      ::tools::run_length(prime_factors.begin(), prime_factors.end(), ::std::back_inserter(distinct_prime_factors));
      for (const auto& [p, q] : distinct_prime_factors) {
        this->m_cpps.emplace_back(p, q);
      }
    }

    M fact(const long long n) const {
      assert(n >= 0);
      ::std::vector<::std::pair<int, int>> rs;
      for (const auto& cpp : this->m_cpps) rs.emplace_back(cpp.fact(n), cpp.m);
      return ::tools::garner<M>(rs.begin(), rs.end()).first;
    }
    M binomial(const long long n, const long long r) const {
      if (r < 0) return M::raw(0);
      if (0 <= n && n < r) return M::raw(0);
      if (n < 0) return M((r & 1) ? -1 : 1) * this->binomial(-n + r - 1, r);

      ::std::vector<::std::pair<int, int>> rs;
      for (const auto& cpp : this->m_cpps) rs.emplace_back(cpp.combination(n, r), cpp.m);
      return ::tools::garner<M>(rs.begin(), rs.end()).first;
    }
    M combination(const long long n, const long long r) const {
      if (!(0 <= r && r <= n)) return M::raw(0);
      return this->binomial(n, r);
    }
    M permutation(const long long n, const long long r) const {
      if (!(0 <= r && r <= n)) return M::raw(0);
      return this->binomial(n, r) * this->fact(r);
    }
    M combination_with_repetition(const long long n, const long long r) const {
      if (n < 0 || r < 0) return M::raw(0);
      return this->binomial(n + r - 1, r);
    }
  };
}

#endif
#line 1 "tools/extended_lucas.hpp"



#include <vector>
#include <cassert>
#include <utility>
#include <iterator>
#line 1 "tools/int128_t.hpp"



#line 1 "tools/detail/int128_t.hpp"



#include <algorithm>
#line 6 "tools/detail/int128_t.hpp"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <limits>
#include <string>
#include <string_view>
#line 1 "tools/abs.hpp"



namespace tools {
  constexpr float abs(const float x) {
    return x < 0 ? -x : x;
  }
  constexpr double abs(const double x) {
    return x < 0 ? -x : x;
  }
  constexpr long double abs(const long double x) {
    return x < 0 ? -x : x;
  }
  constexpr int abs(const int x) {
    return x < 0 ? -x : x;
  }
  constexpr long abs(const long x) {
    return x < 0 ? -x : x;
  }
  constexpr long long abs(const long long x) {
    return x < 0 ? -x : x;
  }
  constexpr unsigned int abs(const unsigned int x) {
    return x;
  }
  constexpr unsigned long abs(const unsigned long x) {
    return x;
  }
  constexpr unsigned long long abs(const unsigned long long x) {
    return x;
  }
}


#line 1 "tools/bit_ceil.hpp"



#include <bit>
#line 6 "tools/bit_ceil.hpp"
#include <type_traits>
#line 1 "tools/is_integral.hpp"



#line 5 "tools/is_integral.hpp"

namespace tools {
  template <typename T>
  struct is_integral : ::std::is_integral<T> {};

  template <typename T>
  inline constexpr bool is_integral_v = ::tools::is_integral<T>::value;
}


#line 1 "tools/is_signed.hpp"



#line 5 "tools/is_signed.hpp"

namespace tools {
  template <typename T>
  struct is_signed : ::std::is_signed<T> {};

  template <typename T>
  inline constexpr bool is_signed_v = ::tools::is_signed<T>::value;
}


#line 1 "tools/make_unsigned.hpp"



#line 5 "tools/make_unsigned.hpp"

namespace tools {
  template <typename T>
  struct make_unsigned : ::std::make_unsigned<T> {};

  template <typename T>
  using make_unsigned_t = typename ::tools::make_unsigned<T>::type;
}


#line 10 "tools/bit_ceil.hpp"

namespace tools {
  template <typename T>
  constexpr T bit_ceil(T) noexcept;

  template <typename T>
  constexpr T bit_ceil(const T x) noexcept {
    static_assert(::tools::is_integral_v<T> && !::std::is_same_v<::std::remove_cv_t<T>, bool>);
    if constexpr (::tools::is_signed_v<T>) {
      assert(x >= 0);
      return ::tools::bit_ceil<::tools::make_unsigned_t<T>>(x);
    } else {
      return ::std::bit_ceil(x);
    }
  }
}


#line 1 "tools/bit_floor.hpp"



#line 10 "tools/bit_floor.hpp"

namespace tools {
  template <typename T>
  constexpr T bit_floor(T) noexcept;

  template <typename T>
  constexpr T bit_floor(const T x) noexcept {
    static_assert(::tools::is_integral_v<T> && !::std::is_same_v<::std::remove_cv_t<T>, bool>);
    if constexpr (::tools::is_signed_v<T>) {
      assert(x >= 0);
      return ::tools::bit_floor<::tools::make_unsigned_t<T>>(x);
    } else {
      return ::std::bit_floor(x);
    }
  }
}


#line 1 "tools/bit_width.hpp"



#line 10 "tools/bit_width.hpp"

namespace tools {
  template <typename T>
  constexpr int bit_width(T) noexcept;

  template <typename T>
  constexpr int bit_width(const T x) noexcept {
    static_assert(::tools::is_integral_v<T> && !::std::is_same_v<::std::remove_cv_t<T>, bool>);
    if constexpr (::tools::is_signed_v<T>) {
      assert(x >= 0);
      return ::tools::bit_width<::tools::make_unsigned_t<T>>(x);
    } else {
      return ::std::bit_width(x);
    }
  }
}


#line 1 "tools/countr_zero.hpp"



#line 12 "tools/countr_zero.hpp"

namespace tools {
  template <typename T>
  constexpr int countr_zero(const T x) noexcept {
    static_assert(::tools::is_integral_v<T> && !::std::is_same_v<::std::remove_cv_t<T>, bool>);
    if constexpr (::tools::is_signed_v<T>) {
      assert(x >= 0);
      return ::std::min(::tools::countr_zero<::tools::make_unsigned_t<T>>(x), ::std::numeric_limits<T>::digits);
    } else {
      return ::std::countr_zero(x);
    }
  }
}


#line 1 "tools/is_unsigned.hpp"



#line 5 "tools/is_unsigned.hpp"

namespace tools {
  template <typename T>
  struct is_unsigned : ::std::is_unsigned<T> {};

  template <typename T>
  inline constexpr bool is_unsigned_v = ::tools::is_unsigned<T>::value;
}


#line 1 "tools/hash_combine.hpp"



#line 6 "tools/hash_combine.hpp"

// Source: https://github.com/google/cityhash/blob/f5dc54147fcce12cefd16548c8e760d68ac04226/src/city.h
// License: MIT
// Author: Google Inc.

// Copyright (c) 2011 Google, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

namespace tools {
  template <typename T>
  void hash_combine(::std::size_t& seed, const T& v) {
    static const ::std::hash<T> hasher;
    static constexpr ::std::size_t k_mul = 0x9ddfea08eb382d69ULL;
    ::std::size_t a = (hasher(v) ^ seed) * k_mul;
    a ^= (a >> 47);
    ::std::size_t b = (seed ^ a) * k_mul;
    b ^= (b >> 47);
    seed = b * k_mul;
  }
}


#line 1 "tools/make_signed.hpp"



#line 5 "tools/make_signed.hpp"

namespace tools {
  template <typename T>
  struct make_signed : ::std::make_signed<T> {};

  template <typename T>
  using make_signed_t = typename ::tools::make_signed<T>::type;
}


#line 1 "tools/now.hpp"



#include <chrono>

namespace tools {
  inline long long now() {
    return ::std::chrono::duration_cast<::std::chrono::nanoseconds>(::std::chrono::high_resolution_clock::now().time_since_epoch()).count();
  }
}


#line 25 "tools/detail/int128_t.hpp"

namespace tools {
  using uint128_t = unsigned __int128;
  using int128_t = __int128;

  namespace detail {
    namespace int128_t {
      constexpr ::tools::uint128_t parse_unsigned(const ::std::string_view s) noexcept {
        assert(!s.empty());
        ::tools::uint128_t x = 0;
        ::std::size_t i = s[0] == '+';
        if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
          for (i += 2; i < s.size(); ++i) {
            assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
            x <<= 4;
            if ('0' <= s[i] && s[i] <= '9') {
              x |= s[i] - '0';
            } else if ('a' <= s[i] && s[i] <= 'f') {
              x |= s[i] - 'a' + 10;
            } else {
              x |= s[i] - 'A' + 10;
            }
          }
        } else {
          for (; i < s.size(); ++i) {
            assert('0' <= s[i] && s[i] <= '9');
            x *= 10;
            x += s[i] - '0';
          }
        }
        return x;
      }

      constexpr ::tools::int128_t parse_signed(const ::std::string_view s) noexcept {
        assert(!s.empty());
        ::tools::int128_t x = 0;
        if (s[0] == '-') {
          ::std::size_t i = 1;
          if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
            for (i += 2; i < s.size(); ++i) {
              assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
              x *= 16;
              if ('0' <= s[i] && s[i] <= '9') {
                x -= s[i] - '0';
              } else if ('a' <= s[i] && s[i] <= 'f') {
                x -= s[i] - 'a' + 10;
              } else {
                x -= s[i] - 'A' + 10;
              }
            }
          } else {
            for (; i < s.size(); ++i) {
              assert('0' <= s[i] && s[i] <= '9');
              x *= 10;
              x -= s[i] - '0';
            }
          }
        } else {
          ::std::size_t i = s[0] == '+';
          if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
            for (i += 2; i < s.size(); ++i) {
              assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
              x <<= 4;
              if ('0' <= s[i] && s[i] <= '9') {
                x |= s[i] - '0';
              } else if ('a' <= s[i] && s[i] <= 'f') {
                x |= s[i] - 'a' + 10;
              } else {
                x |= s[i] - 'A' + 10;
              }
            }
          } else {
            for (; i < s.size(); ++i) {
              assert('0' <= s[i] && s[i] <= '9');
              x *= 10;
              x += s[i] - '0';
            }
          }
        }
        return x;
      }
    }
  }

  constexpr ::tools::uint128_t abs(const ::tools::uint128_t& x) noexcept {
    return x;
  }
  constexpr ::tools::int128_t abs(const ::tools::int128_t& x) {
    return x >= 0 ? x : -x;
  }
}

#define UINT128_C(c) ::tools::detail::int128_t::parse_unsigned(#c)
#define INT128_C(c) ::tools::detail::int128_t::parse_signed(#c)

inline ::std::istream& operator>>(::std::istream& is, ::tools::uint128_t& x) {
  ::std::string s;
  is >> s;
  x = ::tools::detail::int128_t::parse_unsigned(s);
  return is;
}
inline ::std::istream& operator>>(::std::istream& is, ::tools::int128_t& x) {
  ::std::string s;
  is >> s;
  x = ::tools::detail::int128_t::parse_signed(s);
  return is;
}

inline ::std::ostream& operator<<(::std::ostream& os, ::tools::uint128_t x) {
  ::std::string s;
  if (x > 0) {
    while (x > 0) {
      s.push_back('0' + x % 10);
      x /= 10;
    }
  } else {
    s.push_back('0');
  }

  ::std::ranges::reverse(s);
  return os << s;
}
inline ::std::ostream& operator<<(::std::ostream& os, ::tools::int128_t x) {
  ::std::string s;
  if (x > 0) {
    while (x > 0) {
      s.push_back('0' + x % 10);
      x /= 10;
    }
  } else if (x < 0) {
    while (x < 0) {
      s.push_back('0' + (-(x % 10)));
      x /= 10;
    }
    s.push_back('-');
  } else {
    s.push_back('0');
  }

  ::std::ranges::reverse(s);
  return os << s;
}

#if defined(__GLIBCXX__) && defined(__STRICT_ANSI__)
namespace std {
  template <>
  struct hash<::tools::uint128_t> {
    ::std::size_t operator()(const ::tools::uint128_t& x) const {
      static const ::std::size_t seed = ::tools::now();

      ::std::size_t hash = seed;
      ::tools::hash_combine(hash, static_cast<::std::uint64_t>(x >> 64));
      ::tools::hash_combine(hash, static_cast<::std::uint64_t>(x & ((UINT128_C(1) << 64) - 1)));
      return hash;
    }
  };
  template <>
  struct hash<::tools::int128_t> {
    ::std::size_t operator()(const ::tools::int128_t& x) const {
      static ::std::hash<::tools::uint128_t> hasher;
      return hasher(static_cast<::tools::uint128_t>(x));
    }
  };
}
#endif

namespace tools {
  template <>
  struct is_integral<::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_integral<::tools::uint128_t> : ::std::true_type {};
  template <>
  struct is_integral<const ::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_integral<const ::tools::uint128_t> : ::std::true_type {};
  template <>
  struct is_integral<volatile ::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_integral<volatile ::tools::uint128_t> : ::std::true_type {};
  template <>
  struct is_integral<const volatile ::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_integral<const volatile ::tools::uint128_t> : ::std::true_type {};

  template <>
  struct is_signed<::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_signed<::tools::uint128_t> : ::std::false_type {};
  template <>
  struct is_signed<const ::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_signed<const ::tools::uint128_t> : ::std::false_type {};
  template <>
  struct is_signed<volatile ::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_signed<volatile ::tools::uint128_t> : ::std::false_type {};
  template <>
  struct is_signed<const volatile ::tools::int128_t> : ::std::true_type {};
  template <>
  struct is_signed<const volatile ::tools::uint128_t> : ::std::false_type {};

  template <>
  struct is_unsigned<::tools::int128_t> : ::std::false_type {};
  template <>
  struct is_unsigned<::tools::uint128_t> : ::std::true_type {};
  template <>
  struct is_unsigned<const ::tools::int128_t> : ::std::false_type {};
  template <>
  struct is_unsigned<const ::tools::uint128_t> : ::std::true_type {};
  template <>
  struct is_unsigned<volatile ::tools::int128_t> : ::std::false_type {};
  template <>
  struct is_unsigned<volatile ::tools::uint128_t> : ::std::true_type {};
  template <>
  struct is_unsigned<const volatile ::tools::int128_t> : ::std::false_type {};
  template <>
  struct is_unsigned<const volatile ::tools::uint128_t> : ::std::true_type {};

  template <>
  struct make_signed<::tools::int128_t> {
    using type = ::tools::int128_t;
  };
  template <>
  struct make_signed<::tools::uint128_t> {
    using type = ::tools::int128_t;
  };
  template <>
  struct make_signed<const ::tools::int128_t> {
    using type = const ::tools::int128_t;
  };
  template <>
  struct make_signed<const ::tools::uint128_t> {
    using type = const ::tools::int128_t;
  };
  template <>
  struct make_signed<volatile ::tools::int128_t> {
    using type = volatile ::tools::int128_t;
  };
  template <>
  struct make_signed<volatile ::tools::uint128_t> {
    using type = volatile ::tools::int128_t;
  };
  template <>
  struct make_signed<const volatile ::tools::int128_t> {
    using type = const volatile ::tools::int128_t;
  };
  template <>
  struct make_signed<const volatile ::tools::uint128_t> {
    using type = const volatile ::tools::int128_t;
  };

  template <>
  struct make_unsigned<::tools::int128_t> {
    using type = ::tools::uint128_t;
  };
  template <>
  struct make_unsigned<::tools::uint128_t> {
    using type = ::tools::uint128_t;
  };
  template <>
  struct make_unsigned<const ::tools::int128_t> {
    using type = const ::tools::uint128_t;
  };
  template <>
  struct make_unsigned<const ::tools::uint128_t> {
    using type = const ::tools::uint128_t;
  };
  template <>
  struct make_unsigned<volatile ::tools::int128_t> {
    using type = volatile ::tools::uint128_t;
  };
  template <>
  struct make_unsigned<volatile ::tools::uint128_t> {
    using type = volatile ::tools::uint128_t;
  };
  template <>
  struct make_unsigned<const volatile ::tools::int128_t> {
    using type = const volatile ::tools::uint128_t;
  };
  template <>
  struct make_unsigned<const volatile ::tools::uint128_t> {
    using type = const volatile ::tools::uint128_t;
  };

#if defined(__GLIBCXX__) && defined(__STRICT_ANSI__)
  template <>
  constexpr ::tools::uint128_t bit_ceil<::tools::uint128_t>(::tools::uint128_t x) noexcept {
    if (x <= 1) return 1;
    --x;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    x |= x >> 32;
    x |= x >> 64;
    return ++x;
  }

  template <>
  constexpr ::tools::uint128_t bit_floor<::tools::uint128_t>(::tools::uint128_t x) noexcept {
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    x |= x >> 32;
    x |= x >> 64;
    return x & ~(x >> 1);
  }

  template <>
  constexpr int bit_width<::tools::uint128_t>(::tools::uint128_t x) noexcept {
    int w = 0;
    if (x & UINT128_C(0xffffffffffffffff0000000000000000)) {
      x >>= 64;
      w += 64;
    }
    if (x & UINT128_C(0xffffffff00000000)) {
      x >>= 32;
      w += 32;
    }
    if (x & UINT128_C(0xffff0000)) {
      x >>= 16;
      w += 16;
    }
    if (x & UINT128_C(0xff00)) {
      x >>= 8;
      w += 8;
    }
    if (x & UINT128_C(0xf0)) {
      x >>= 4;
      w += 4;
    }
    if (x & UINT128_C(0xc)) {
      x >>= 2;
      w += 2;
    }
    if (x & UINT128_C(0x2)) {
      x >>= 1;
      w += 1;
    }
    w += x;
    return w;
  }

  namespace detail {
    namespace countr_zero {
      template <::std::size_t N>
      struct ntz_traits;

      template <>
      struct ntz_traits<128> {
        using type = ::tools::uint128_t;
        static constexpr int shift = 120;
        static constexpr type magic = UINT128_C(0x01061438916347932a5cd9d3ead7b77f);
        static constexpr int ntz_table[255] = {
          128,   0,   1,  -1,   2,  -1,   8,  -1,   3,  -1,  15,  -1,   9,  -1,  22,  -1,
            4,  -1,  29,  -1,  16,  -1,  36,  -1,  10,  -1,  43,  -1,  23,  -1,  50,  -1,
            5,  -1,  33,  -1,  30,  -1,  57,  -1,  17,  -1,  64,  -1,  37,  -1,  71,  -1,
           11,  -1,  60,  -1,  44,  -1,  78,  -1,  24,  -1,  85,  -1,  51,  -1,  92,  -1,
           -1,   6,  -1,  20,  -1,  34,  -1,  48,  31,  -1,  -1,  69,  58,  -1,  -1,  90,
           18,  -1,  67,  -1,  65,  -1,  99,  -1,  38,  -1, 101,  -1,  72,  -1, 106,  -1,
           -1,  12,  -1,  40,  -1,  61,  -1,  82,  45,  -1,  -1, 103,  79,  -1, 113,  -1,
           -1,  25,  -1,  74,  86,  -1,  -1, 116,  -1,  52,  -1, 108,  -1,  93,  -1, 120,
          127,  -1,  -1,   7,  -1,  14,  -1,  21,  -1,  28,  -1,  35,  -1,  42,  -1,  49,
           -1,  32,  -1,  56,  -1,  63,  -1,  70,  -1,  59,  -1,  77,  -1,  84,  -1,  91,
           -1,  19,  -1,  47,  -1,  68,  -1,  89,  -1,  66,  -1,  98,  -1, 100,  -1, 105,
           -1,  39,  -1,  81,  -1, 102,  -1, 112,  -1,  73,  -1, 115,  -1, 107,  -1, 119,
          126,  -1,  13,  -1,  27,  -1,  41,  -1,  -1,  55,  62,  -1,  -1,  76,  83,  -1,
           -1,  46,  -1,  88,  -1,  97,  -1, 104,  -1,  80,  -1, 111,  -1, 114,  -1, 118,
          125,  -1,  26,  -1,  54,  -1,  75,  -1,  -1,  87,  96,  -1,  -1, 110,  -1, 117,
          124,  -1,  53,  -1,  -1,  95, 109,  -1, 123,  -1,  94,  -1, 122,  -1, 121
        };
      };

      template <typename T>
      constexpr int impl(const T x) noexcept {
        using tr = ::tools::detail::countr_zero::ntz_traits<::std::numeric_limits<T>::digits>;
        using type = typename tr::type;
        return tr::ntz_table[static_cast<type>(tr::magic * static_cast<type>(x & -x)) >> tr::shift];
      }
    }
  }

  template <>
  constexpr int countr_zero<::tools::uint128_t>(const ::tools::uint128_t x) noexcept {
    return ::tools::detail::countr_zero::impl(x);
  }
#endif
}


#line 5 "tools/int128_t.hpp"


#line 1 "tools/prime_factorization.hpp"



#line 6 "tools/prime_factorization.hpp"
#include <queue>
#line 9 "tools/prime_factorization.hpp"
#include <cmath>
#include <numeric>
#line 1 "tools/is_prime.hpp"



#include <array>
#line 1 "tools/prod_mod.hpp"



#line 1 "tools/uint128_t.hpp"



#line 5 "tools/uint128_t.hpp"


#line 5 "tools/prod_mod.hpp"

namespace tools {

  template <typename T1, typename T2, typename T3>
  constexpr T3 prod_mod(const T1 x, const T2 y, const T3 m) {
    using u128 = ::tools::uint128_t;
    u128 prod_mod = u128(x >= 0 ? x : -x) * u128(y >= 0 ? y : -y) % u128(m);
    if ((x >= 0) ^ (y >= 0)) prod_mod = u128(m) - prod_mod;
    return prod_mod;
  }
}


#line 1 "tools/pow_mod.hpp"



#line 1 "tools/mod.hpp"



#line 7 "tools/mod.hpp"

namespace tools {

  template <typename M, typename N> requires (
    ::tools::is_integral_v<M> && !::std::is_same_v<::std::remove_cv_t<M>, bool> &&
    ::tools::is_integral_v<N> && !::std::is_same_v<::std::remove_cv_t<N>, bool>)
  constexpr ::std::common_type_t<M, N> mod(const M a, const N b) noexcept {
    assert(b != 0);

    using UM = ::std::make_unsigned_t<M>;
    using UN = ::std::make_unsigned_t<N>;
    const UM ua = a >= 0 ? a : static_cast<UM>(-(a + 1)) + 1;
    const UN ub = b >= 0 ? b : static_cast<UN>(-(b + 1)) + 1;
    auto r = ua % ub;
    if (a < 0 && r > 0) {
      r = ub - r;
    }
    return r;
  }
}


#line 6 "tools/pow_mod.hpp"

namespace tools {

  template <typename T1, typename T2, typename T3>
  constexpr T3 pow_mod(const T1 x, T2 n, const T3 m) {
    if (m == 1) return 0;
    T3 r = 1;
    T3 y = ::tools::mod(x, m);
    while (n > 0) {
      if ((n & 1) > 0) {
        r = ::tools::prod_mod(r, y, m);
      }
      y = ::tools::prod_mod(y, y, m);
      n /= 2;
    }
    return r;
  }
}


#line 7 "tools/is_prime.hpp"

namespace tools {

  constexpr bool is_prime(const unsigned long long n) {
    constexpr ::std::array<unsigned long long, 7> bases = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};

    if (n <= 1) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;

    auto d = n - 1;
    for (; d % 2 == 0; d /= 2);

    for (const auto a : bases) {
      if (a % n == 0) return true;

      auto power = d;
      auto target = ::tools::pow_mod(a, power, n);

      bool is_composite = true;
      if (target == 1) is_composite = false;
      for (; is_composite && power != n - 1; power *= 2, target = ::tools::prod_mod(target, target, n)) {
        if (target == n - 1) is_composite = false;
      }

      if (is_composite) {
        return false;
      }
    }

    return true;
  }
}


#line 1 "tools/pow2.hpp"



#line 6 "tools/pow2.hpp"

namespace tools {

  template <typename T, typename ::std::enable_if<::std::is_unsigned<T>::value, ::std::nullptr_t>::type = nullptr>
  constexpr T pow2(const T x) {
    return static_cast<T>(1) << x;
  }

  template <typename T, typename ::std::enable_if<::std::is_signed<T>::value, ::std::nullptr_t>::type = nullptr>
  constexpr T pow2(const T x) {
    return static_cast<T>(static_cast<typename ::std::make_unsigned<T>::type>(1) << static_cast<typename ::std::make_unsigned<T>::type>(x));
  }
}


#line 1 "tools/floor_log2.hpp"



#line 6 "tools/floor_log2.hpp"

namespace tools {
  template <typename T>
  constexpr T floor_log2(T x) noexcept {
    assert(x > 0);
    return ::tools::bit_width(x) - 1;
  }
}


#line 15 "tools/prime_factorization.hpp"

namespace tools {

  template <typename T>
  ::std::vector<T> prime_factorization(T n) {
    assert(1 <= n && n <= 1000000000000000000);
    ::std::vector<T> result;

    if (n == 1) return result;

    ::std::queue<::std::pair<T, T>> factors({::std::pair<T, T>(n, 1)});
    while (!factors.empty()) {
      const T factor = factors.front().first;
      const T occurrences = factors.front().second;
      factors.pop();
      if (::tools::is_prime(factor)) {
        for (T i = 0; i < occurrences; ++i) {
          result.push_back(factor);
        }
      } else {
        const T m = ::tools::pow2((::tools::floor_log2(factor) + 1) / 8);
        for (T c = 1; ; ++c) {
          const auto f = [&](T& x) {
            x = ::tools::prod_mod(x, x, factor);
            x += c;
            if (x >= factor) x -= factor;
          };
          T y = 2;
          T r = 1;
          T q = 1;
          T x, g, ys;
          do {
            x = y;
            for (T i = 0; i < r; ++i) {
              f(y);
            }
            T k = 0;
            do {
              ys = y;
              for (T i = 0; i < ::std::min(m, r - k); ++i) {
                f(y);
                q = ::tools::prod_mod(q, ::std::abs(x - y), factor);
              }
              g = ::std::gcd(q, factor);
              k += m;
            } while (k < r && g == 1);
            r *= 2;
          } while (g == 1);
          if (g == factor) {
            do {
              f(ys);
              g = ::std::gcd(::std::abs(x - ys), factor);
            } while (g == 1);
          }
          if (g < factor) {
            T h = factor / g;
            if (h < g) ::std::swap(g, h);
            T n = 1;
            while (h % g == 0) {
              h /= g;
              ++n;
            }
            factors.emplace(g, occurrences * n);
            if (h > 1) factors.emplace(h, occurrences);
            break;
          }
        }
      }
    }

    ::std::sort(result.begin(), result.end());
    return result;
  }
}


#line 1 "tools/run_length.hpp"



#line 8 "tools/run_length.hpp"

namespace tools {
  template <typename InputIterator, typename OutputIterator>
  void run_length(const InputIterator& begin, const InputIterator& end, OutputIterator result) {
    using T = typename ::std::iterator_traits<InputIterator>::value_type;
    if (begin == end) return;

    ::std::pair<T, ::std::size_t> prev;
    for (auto [it, breaks] = ::std::make_pair(begin, false); !breaks; breaks = it == end, it = ::std::next(it, breaks ? 0 : 1)) {
      bool flg1, flg2;
      if (it == begin) {
        flg1 = false;
        flg2 = true;
      } else if (it == end) {
        flg1 = true;
        flg2 = false;
      } else if (*it != prev.first) {
        flg1 = true;
        flg2 = true;
      } else {
        flg1 = false;
        flg2 = false;
      }
      if (flg1 || flg2) {
        if (flg1) {
          *result = prev;
          ++result;
        }
        if (flg2) {
          prev.first = *it;
          prev.second = 1;
        }
      } else {
        ++prev.second;
      }
    }
  }
}


#line 1 "tools/garner.hpp"



#line 1 "tools/inv_mod.hpp"



#line 1 "tools/extgcd.hpp"



#include <tuple>
#line 9 "tools/extgcd.hpp"

namespace tools {

  template <typename T>
  ::std::tuple<T, T, T> extgcd(T prev_r, T r) {
    const bool prev_r_is_neg = prev_r < T(0);
    const bool r_is_neg = r < T(0);

    if (prev_r_is_neg) prev_r = -prev_r;
    if (r_is_neg) r = -r;

    #ifndef NDEBUG
    const T a = prev_r;
    const T b = r;
    #endif

    T prev_s(1);
    T prev_t(0);
    T s(0);
    T t(1);
    while (r != T(0)) {
      const T q = prev_r / r;
      ::std::tie(prev_r, r) = ::std::make_pair(r, prev_r - q * r);
      ::std::tie(prev_s, s) = ::std::make_pair(s, prev_s - q * s);
      ::std::tie(prev_t, t) = ::std::make_pair(t, prev_t - q * t);
    }

    if (prev_r_is_neg) prev_s = -prev_s;
    if (r_is_neg) prev_t = -prev_t;

    assert(::tools::abs(prev_s) <= ::std::max(b / prev_r / T(2), T(1)));
    assert(::tools::abs(prev_t) <= ::std::max(a / prev_r / T(2), T(1)));
    return ::std::make_tuple(prev_s, prev_t, prev_r);
  }
}


#line 7 "tools/inv_mod.hpp"

namespace tools {

  template <typename T1, typename T2>
  constexpr T2 inv_mod(const T1 x, const T2 m) {
    const auto [x0, y0, gcd] = ::tools::extgcd(x, m);
    assert(gcd == 1);
    return ::tools::mod(x0, m);
  }
}


#line 9 "tools/garner.hpp"

// Source: https://qiita.com/drken/items/ae02240cd1f8edfc86fd
// License: unknown
// Author: drken

namespace tools {

  template <typename Iterator, typename ModType>
  ::std::pair<long long, long long> garner(const Iterator& begin, const Iterator& end, const ModType& mod) {
    ::std::vector<long long> b, m;
    for (auto it = begin; it != end; ++it) {
      b.push_back(::tools::mod(it->first, it->second));
      m.push_back(it->second);
    }

    auto lcm = 1LL;
    for (::std::size_t i = 0; i < b.size(); ++i) {
      (lcm *= m[i]) %= mod;
    }

    m.push_back(mod);
    ::std::vector<long long> coeffs(m.size(), 1);
    ::std::vector<long long> constants(m.size(), 0);
    for (::std::size_t k = 0; k < b.size(); ++k) {
      long long t = ::tools::mod((b[k] - constants[k]) * ::tools::inv_mod(coeffs[k], m[k]), m[k]);
      for (::std::size_t i = k + 1; i < m.size(); ++i) {
        (constants[i] += t * coeffs[i]) %= m[i];
        (coeffs[i] *= m[k]) %= m[i];
      }
    }

    return ::std::make_pair(constants.back(), lcm);
  }

  template <typename M, typename Iterator>
  ::std::pair<M, M> garner(const Iterator& begin, const Iterator& end) {
    const auto [y, z] = ::tools::garner(begin, end, M::mod());
    return ::std::make_pair(M::raw(y), M::raw(z));
  }
}


#line 12 "tools/extended_lucas.hpp"

// Source: https://hitonanode.github.io/cplib-cpp/number/combination.hpp.html
// License: MIT
// Author: hitonanode

// MIT License
// 
// Copyright (c) 2019 Ryotaro Sato
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

namespace tools {

  template <class M>
  class extended_lucas {
    struct combination_prime_pow {
      int p, q, m;
      ::std::vector<int> fac, invfac, ppow;

      long long ej(long long n) const {
        long long ret = 0;
        while (n) ret += n, n /= this->p;
        return ret;
      }

      combination_prime_pow(const int p_, const int q_) : p(p_), q(q_), m(1), ppow{1} {
        for (int t = 0; t < this->q; ++t) this->m *= this->p, this->ppow.push_back(this->m);
        this->fac.assign(this->m, 1);
        this->invfac.assign(this->m, 1);
        for (int i = 1; i < this->m; ++i) this->fac[i] = static_cast<long long>(this->fac[i - 1]) * (i % this->p ? i : 1) % this->m;
        this->invfac[this->m - 1] = this->fac[this->m - 1]; // Same as Wilson's theorem
        assert(1LL * this->fac.back() * this->invfac.back() % this->m == 1);
        for (int i = this->m - 1; i; --i) this->invfac[i - 1] = static_cast<long long>(this->invfac[i]) * (i % this->p ? i : 1) % this->m;
      }

      int fact(const long long n) const {
        assert(n >= 0);
        const auto q0 = this->ej(n / this->p);
        return q0 < this->q ? static_cast<long long>(this->fac[n]) * this->ppow[q0] % this->m : 0;
      }

      int combination(long long n, long long r) const {
        assert(0 <= r && r <= n);
        if (this->p == 2 && this->q == 1) return !((~n) & r); // Lucas
        long long k = n - r;
        const long long e0 = this->ej(n / this->p) - this->ej(r / this->p) - this->ej(k / this->p);
        if (e0 >= q) return 0;

        long long ret = this->ppow[e0];
        if (this->q == 1) { // Lucas
          while (n) {
            ret = ::tools::int128_t(ret) * this->fac[n % this->p] * this->invfac[r % this->p] * this->invfac[k % this->p] % this->p;
            n /= this->p, r /= this->p, k /= this->p;
          }
          return static_cast<int>(ret);
        } else {
          if ((p > 2 || q < 3) && (this->ej(n / this->m) - this->ej(r / this->m) - this->ej(k / this->m)) & 1) ret = this->m - ret;
          while (n) {
            ret = ::tools::int128_t(ret) * this->fac[n % this->m] * this->invfac[r % this->m] * this->invfac[k % this->m] % this->m;
            n /= this->p, r /= this->p, k /= this->p;
          }
          return static_cast<int>(ret);
        }
      }
    };

    ::std::vector<combination_prime_pow> m_cpps;

  public:
    extended_lucas() {
      const auto prime_factors = ::tools::prime_factorization(M::mod());
      ::std::vector<::std::pair<int, int>> distinct_prime_factors;
      ::tools::run_length(prime_factors.begin(), prime_factors.end(), ::std::back_inserter(distinct_prime_factors));
      for (const auto& [p, q] : distinct_prime_factors) {
        this->m_cpps.emplace_back(p, q);
      }
    }

    M fact(const long long n) const {
      assert(n >= 0);
      ::std::vector<::std::pair<int, int>> rs;
      for (const auto& cpp : this->m_cpps) rs.emplace_back(cpp.fact(n), cpp.m);
      return ::tools::garner<M>(rs.begin(), rs.end()).first;
    }
    M binomial(const long long n, const long long r) const {
      if (r < 0) return M::raw(0);
      if (0 <= n && n < r) return M::raw(0);
      if (n < 0) return M((r & 1) ? -1 : 1) * this->binomial(-n + r - 1, r);

      ::std::vector<::std::pair<int, int>> rs;
      for (const auto& cpp : this->m_cpps) rs.emplace_back(cpp.combination(n, r), cpp.m);
      return ::tools::garner<M>(rs.begin(), rs.end()).first;
    }
    M combination(const long long n, const long long r) const {
      if (!(0 <= r && r <= n)) return M::raw(0);
      return this->binomial(n, r);
    }
    M permutation(const long long n, const long long r) const {
      if (!(0 <= r && r <= n)) return M::raw(0);
      return this->binomial(n, r) * this->fact(r);
    }
    M combination_with_repetition(const long long n, const long long r) const {
      if (n < 0 || r < 0) return M::raw(0);
      return this->binomial(n + r - 1, r);
    }
  };
}


Back to top page