結果

問題 No.109 N! mod M
ユーザー shinchanshinchan
提出日時 2022-12-13 22:46:29
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,555 bytes
コンパイル時間 2,016 ms
コンパイル使用メモリ 201,368 KB
実行使用メモリ 8,576 KB
最終ジャッジ日時 2024-04-25 06:19:47
合計ジャッジ時間 8,771 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
#define be(v) (v).begin(),(v).end()
#define pb(q) push_back(q)
#define rep(i, n) for(int i=0;i<n;i++)
#define all(i, v) for(auto& i : v)
typedef long long ll;
using namespace std;
const ll mod=1000000007, INF=(1LL<<60);
#define doublecout(a) cout<<fixed<<setprecision(10)<<a<<endl;


map<ll, ll> prime(ll n) {
    map<ll, ll> mp;
    ll m = n;
    for(ll i = 2; i * i <= n; i ++) {
        while(m % i == 0) {
            mp[i] ++;
            m /= i;
        }
    } 
    if(m > 1) mp[m]++;
    return mp;
}



long long modinv(long long a, long long m) {
    long long b = m, u = 1, v = 0;
    while (b) {
        long long t = a / b;
        a -= t * b; swap(a, b);
        u -= t * v; swap(u, v);
    }
    u %= m; 
    if (u < 0) u += m;
    return u;
}

void solve() {
    ll n, m;
    cin >> n >> m;
    ll ans = 1;
    if(n >= m) {
        cout << 0 << endl;
        return;
    }
    if(n <= 300001) {
        for(ll i = 1; i <= n; i ++) {
            ans *= i;
            ans %= m;
        }
        cout << ans << endl;
        return;
    }
    for(auto [x, y] : prime(m)) {
        if(x == m) {
            ll num = m - 1;
            for(ll i = m - 1; i > n; i ++) {
                num *= i;
                num %= m;
            }
            cout << modinv(num, m) << endl;
            return;
        }
        cout << 0 << endl;
        return;
    }
    return ;
}
int main() {
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false); 
    ll t;
    cin >> t;
    while(t--) solve();
    return 0; 
}
0