結果

問題 No.109 N! mod M
ユーザー shinchanshinchan
提出日時 2022-12-13 23:35:37
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 106 ms / 5,000 ms
コード長 1,673 bytes
コンパイル時間 2,255 ms
コンパイル使用メモリ 198,440 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-25 06:51:15
合計ジャッジ時間 2,964 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

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;


vector<pair<ll, ll>> prime(ll n) {
    vector<pair<ll, ll>> v;
    ll m = n;
    for(ll i = 2; i * i <= n; i ++) {
        ll num = 0;
        while(m % i == 0) {
            num ++;
            m /= i;
        }
        if(num > 0) {
            v.push_back({i, num});
        }
    } 
    if(m > 1) v.push_back({m, 1});
    return v;
}



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 % m << 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); 
    int t;
    cin >> t;
    while(t--) solve();
    return 0; 
}
0