結果

問題 No.109 N! mod M
ユーザー mayoko_mayoko_
提出日時 2014-12-22 12:51:02
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 1,457 ms / 5,000 ms
コード長 1,429 bytes
コンパイル時間 507 ms
コンパイル使用メモリ 73,620 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 05:22:04
合計ジャッジ時間 2,747 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>

#define INF 1000000000

using namespace std;
typedef long long ll;

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

// extgcd
ll extgcd(ll a, ll b, ll& x, ll& y) {
    ll d = a;
    if (b != 0) {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1; y = 0;
    }
    return d;
}

// mod_inverse
ll mod_inverse(ll a, ll m) {
    ll x, y;
    extgcd(a, m, x, y);
    return (m+x%m) % m;
}

int main(void) {
    int T;
    cin >> T;
    while (T--) {
        int N, M;
        cin >> N >> M;
        if (N >= M) {
            cout << 0 << endl;
            continue;
        }
        if (M <= 2*100000) {
            ll ans = 1;
            for (ll i = 1; i <= N; i++) {
                ans = (ans*i) % M;
            }
            cout << ans % M << endl;
            continue;
        }
        if (!isPrime(M)) {
            cout << 0 << endl;
        } else {
            ll ans = M-1;
            for (ll i = N+1; i <= M-1; i++) {
                ans = (ans * mod_inverse(i, M)) % M;
            }
            cout << ans << endl;
        }
    }
    return 0;
}
0