結果

問題 No.109 N! mod M
ユーザー shinchanshinchan
提出日時 2021-10-26 18:54:36
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 1,216 ms / 5,000 ms
コード長 1,799 bytes
コンパイル時間 2,182 ms
コンパイル使用メモリ 206,988 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-07-28 08:51:17
合計ジャッジ時間 4,303 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 58 ms
4,376 KB
testcase_02 AC 24 ms
4,380 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 38 ms
4,376 KB
testcase_05 AC 1,216 ms
4,380 KB
testcase_06 AC 14 ms
4,376 KB
testcase_07 AC 109 ms
4,376 KB
testcase_08 AC 2 ms
4,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;


map<ll, ll> prime(ll n) {
    ll m = n;
    map<ll, ll> mp;
    for(ll i=2;i*i<=n;i++) {
        while(m % i == 0) {
            m /= i;
            mp[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;
    if(n >= m || m == 1) {
        cout << 0 << endl;
        return;
    }
    if(n == 0) {
        cout << 1 << endl;
        return;
    }
    int cnt = 0;
    map<ll, ll> mp = prime(m);
    {
        bool ok = true;
        
        for(auto [x, y] : mp) {
            cnt += y;
            ll e = n;
            rep(i, y) {
                if(e < x) ok = false;
                e /= x;
            }
        }
        if(ok) {
            cout << 0 << endl;
            return;
        }
    } 
    ll ans = 1;
    if(cnt == 1) {
        ans = -1;
        for(ll i=n+1;i<m;i++) {
            ans *= modinv(i, m);
            ans %= m;
        }
        ans += m;
        ans %= m;
        cout << ans << endl;
        return;
    }
    for(ll i=2;i<=n;i++) {
        ans *= i;
        ans %= m;
    }
    cout << ans << endl;
}

int main() {
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);
    ll t;
    cin >> t;
    while(t--) solve();
    return 0;
}


0