結果

問題 No.109 N! mod M
ユーザー PachicobuePachicobue
提出日時 2017-08-14 00:04:58
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 110 ms / 5,000 ms
コード長 2,174 bytes
コンパイル時間 1,557 ms
コンパイル使用メモリ 165,388 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-03 12:41:35
合計ジャッジ時間 2,534 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 77 ms
4,376 KB
testcase_02 AC 98 ms
4,376 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 3 ms
4,376 KB
testcase_05 AC 110 ms
4,376 KB
testcase_06 AC 13 ms
4,380 KB
testcase_07 AC 12 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

// {{{ Templates
#include <bits/stdc++.h>

#define show(x) cerr << #x << " = " << x << endl

using namespace std;
using ll = long long;
using pii = pair<int, int>;
using vi = vector<int>;

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
    os << "sz:" << v.size() << "\n[";
    for (const auto& p : v) {
        os << p << ",";
    }
    os << "]\n";
    return os;
}

template <typename S, typename T>
ostream& operator<<(ostream& os, const pair<S, T>& p)
{
    os << "(" << p.first << "," << p.second
       << ")";
    return os;
}


constexpr ll MOD = (ll)1e9 + 7LL;

template <typename T>
constexpr T INF = numeric_limits<T>::max() / 100;

// }}}

template <typename T>
T extgcd(const T a, const T b, T& x, T& y)  // ax+by=gcd(a,b)
{
    T d = a;
    if (b != 0) {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1;
        y = 0;
    }
    return d;
}

inline bool isprime(const ll n)
{
    for (ll i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

constexpr ll LIMIT = 200000;

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int T;
    cin >> T;
    for (int t = 0; t < T; t++) {
        ll N, M;
        cin >> N >> M;
        if (N == 0) {
            cout << 1 % M << endl;
            continue;
        }

        if (N >= M) {
            cout << 0 << endl;
            continue;
        }
        if (N <= LIMIT) {
            ll prod = 1;
            for (ll i = 1; i <= N; i++) {
                prod = (prod * i) % M;
            }
            cout << prod << endl;
        } else {
            if (not isprime(M)) {
                cout << 0 << endl;
            } else {
                ll prod = 1;
                for (ll i = N + 1; i <= M - 1; i++) {
                    prod = (prod * i) % M;
                }
                ll inv = 0;
                ll tmp = 0;
                extgcd(prod, M, inv, tmp);
                inv = ((inv % M) + M) % M;
                assert((inv * prod) % M == 1);
                cout << (inv * (M - 1)) % M << endl;
            }
        }
    }

    return 0;
}
0