結果

問題 No.109 N! mod M
ユーザー maine_honzukimaine_honzuki
提出日時 2020-05-14 17:22:36
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,191 bytes
コンパイル時間 1,505 ms
コンパイル使用メモリ 166,624 KB
実行使用メモリ 4,352 KB
最終ジャッジ日時 2023-10-13 16:04:45
合計ジャッジ時間 8,109 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

bool isprime(long long x) {
    for (long long i = 2; i * i <= x; i++) {
        if (x % i == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    int T;
    cin >> T;
    while (T--) {
        long long N, M;
        cin >> N >> M;

        if (N < 1e5) {
            long long ans = 1;
            for (int i = 2; i <= N; i++) {
                (ans *= i) %= M;
            }
            cout << ans << endl;
            continue;
        }

        if (N >= M || M == 1) {
            cout << 0 << endl;
            continue;
        }

        if (!isprime(M)) {
            cout << 0 << endl;
            continue;
        }

        auto modpow = [&](long long a, long long n) {
            long long t = 1;
            while (n) {
                if (n & 1)
                    (t *= a) %= M;
                (a *= a) %= M;
            }
            return t;
        };
        auto inv = [&](long long a) {
            return modpow(a, M - 2);
        };

        long long ans = M - 1;
        for (long long i = M - 2; i > N; i--)
            (ans *= inv(i)) %= M;
        cout << ans << endl;
    }
}
0