結果

問題 No.109 N! mod M
ユーザー maine_honzukimaine_honzuki
提出日時 2020-05-14 17:29:59
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 2,963 ms / 5,000 ms
コード長 1,217 bytes
コンパイル時間 1,706 ms
コンパイル使用メモリ 166,408 KB
実行使用メモリ 4,372 KB
最終ジャッジ日時 2023-10-13 16:10:15
合計ジャッジ時間 5,794 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ(β)

テストケース

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

ソースコード

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 >= M || M == 1) {
            cout << 0 << endl;
            continue;
        }

        if (N < 1e5) {
            long long ans = 1;
            for (int i = 2; i <= N; i++) {
                (ans *= i) %= M;
            }
            cout << ans << 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;
                n >>= 1;
            }
            return t;
        };
        auto inv = [&](long long a) {
            return modpow(a, M - 2);
        };

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