結果

問題 No.109 N! mod M
ユーザー Mi_SawaMi_Sawa
提出日時 2015-04-08 22:55:32
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,838 bytes
コンパイル時間 1,139 ms
コンパイル使用メモリ 146,520 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-17 18:56:23
合計ジャッジ時間 3,294 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
#define all(x) begin(x),end(x)
#define rall(x) (x).rbegin(),(x).rend()
#define REP(i,b,n) for(int i=(int)(b);i<(int)(n);++i)
#define rep(i,n) REP(i,0,n)
#define repsz(i,v) rep(i,(v).size())
#define aur auto&
#define bit(n) (1LL<<(n))
#define eb emplace_back
#define mt make_tuple
#define fst first
#define snd second
using namespace std;
typedef long long ll;
//#define int long long
template<class C>int size(const C &c){ return c.size(); }
template<class T>bool chmin(T&a,const T&b){if(a<=b)return false;a=b;return true;}
template<class T>bool chmax(T&a,const T&b){if(a>=b)return false;a=b;return true;}

bool is_prime(ll n){
    for(int p = 2; p * p <= n; ++p) if(n % p == 0) return false;
    return true;
}
ll exgcd(ll a, ll b, ll &x, ll &y){//{{{
    ll u[] = {a, 1, 0}, v[] = {b, 0, 1};
    while(*v){
        ll t = *u / *v;
        rep(i, 3) u[i] -= t * v[i];
        swap(u, v);
    }
    if(*u < 0) rep(i, 3) u[i] = -u[i];
    x = u[1]; y = u[2];
    return u[0];
}//}}}
ll invMod(ll a, ll m){//{{{
    ll p, q;
    exgcd(a, m, p, q);
    return (p%m+m)%m;
}//}}}
bool solve(){
    int T;
    cin >> T;
    rep(_, T){
        ll n, m;
        cin >> n >> m;
        if(n >= m){ cout << 0 << endl; continue; }
        if(n < 1000 * 1000){
            ll res = 1;
            rep(i, n+1) if(i) (res *= i) %= m;
            cout << res << endl;
            continue;
        }
        if(!is_prime(m)){ cout << 0 << endl; continue; }
        ll res = -1;
        for(int i = m-1; i > n; --i) (res *= invMod(i, m)) %= m;
        if(res < 0) res += m;
        cout << res << endl;
    }
    return true;
}
signed main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << std::fixed << std::setprecision(10);
    solve();
    return 0;
}
// vim:set foldmethod=marker commentstring=//%s:
0