結果

問題 No.109 N! mod M
コンテスト
ユーザー Hachimori
提出日時 2014-12-23 19:54:26
言語 C++11
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=gnu++11 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
WA  
実行時間 -
コード長 1,129 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 503 ms
コンパイル使用メモリ 74,940 KB
実行使用メモリ 15,944 KB
最終ジャッジ日時 2026-03-05 07:22:18
合計ジャッジ時間 16,249 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 3 WA * 4 TLE * 2
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include<iostream>
using namespace std;


int n, m;

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


bool isPrime(int M) {
    for (int i = 2; i * i <= M; ++i)
        if (M % i == 0)
            return false;
    return true;
}


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;
    }

    if (isPrime(m)) {
        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 {
        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