結果

問題 No.109 N! mod M
ユーザー HachimoriHachimori
提出日時 2014-12-23 18:29:32
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,148 bytes
コンパイル時間 968 ms
コンパイル使用メモリ 53,036 KB
実行使用メモリ 4,372 KB
最終ジャッジ日時 2023-09-02 21:53:47
合計ジャッジ時間 6,520 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include<iostream>
using namespace std;


int n, m;

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


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


int modpow(int p, int nMul, int mod) {
    if (nMul == 0) return 1;
    int t = modpow(p, nMul / 2, mod);
    return nMul & 1 ? 1LL * t * t % mod * p % mod : 1LL * t * t % mod;
}


// 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 ans = m - 1;
        for (int i = m - 1; i > n; --i)
            ans = 1LL * ans * inv(i, m) % m;
        cout << ans << endl;
    }
    else if (n > m / 2) {
        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