結果

問題 No.109 N! mod M
ユーザー HachimoriHachimori
提出日時 2014-12-23 19:52:09
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,434 bytes
コンパイル時間 2,059 ms
コンパイル使用メモリ 61,280 KB
実行使用メモリ 4,372 KB
最終ジャッジ日時 2023-09-02 21:58:23
合計ジャッジ時間 2,173 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include<iostream>
#include<vector>
using namespace std;


int n, m;

void read() {
    cin >> n >> m;
}


vector<int> getFactor(int M) {
    vector<int> factor;
    for (int i = 2; i * i <= M; ++i)
        if (M % i == 0) {
            while (M % i == 0) {
                M /= i;
            }
            factor.push_back(i);
        }
    if (M > 1)
        factor.push_back(M);
    return factor;
}


int modpow(int p, int nMul, int mod) {
    int ret = 1;
    while (nMul) {
        if (nMul & 1) ret = 1LL * ret * p % mod;
        ret = 1LL * ret * ret % mod;
        nMul >>= 1;
    }
    return ret;
}


// mod: 素数
int inv(int num, int mod) {
    return modpow(num, mod - 2, mod);
}


void work() {
    if (n >= m) {
        cout << 0 << endl;
        return;
    }

    vector<int> factor = getFactor(m);
    
    if (factor.size() == 1) {
        int toInv = 1;
        for (int i = m - 1; i > n; --i)
            toInv = 1LL * toInv * i % m;
        cout << 1LL * (m - 1) * inv(toInv, m) % m << endl;
    }
    else if (n > factor.back()) {
        cout << 0 << endl;
    }
    else {
        int ans = 1;
        for (int i = 1; i <= n; ++i) {
            ans = 1LL * ans * i % m;
            if (ans == 0)
                break;
        }
        cout << ans << endl;
    }
}


int main() {
    int cases;
    cin >> cases;
    for (int i = 0; i < cases; ++i) {
        read();
        work();
    }
    return 0;
}
0