結果

問題 No.109 N! mod M
ユーザー 0w10w1
提出日時 2017-01-03 14:38:29
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 100 ms / 5,000 ms
コード長 2,011 bytes
コンパイル時間 1,619 ms
コンパイル使用メモリ 166,572 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 05:37:17
合計ジャッジ時間 2,291 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector< int > vi;
typedef vector< vi > vvi;
typedef vector< ll > vl;
typedef vector< vl > vvl;
typedef pair< int, int > pii;
typedef vector< pii > vp;
typedef vector< double > vd;
typedef vector< vd > vvd;
typedef vector< string > vs;

template< class T1, class T2 >
int upmin( T1 &x, T2 v ){
  if( x > v ){
    x = v;
    return 1;
  }
  return 0;
}

template< class T1, class T2 >
int upmax( T1 &x, T2 v ){
  if( x < v ){
    x = v;
    return 1;
  }
  return 0;
}

const int INF = 0x3f3f3f3f;

void init(){

}

void preprocess(){

}

int is_prime( int x ){
  for( int i = 2; i * i <= x; ++i ){
    if( x % i == 0 ){
      return 0;
    }
  }
  return 1;
}

int bruteforce( int n, int m ){ // modulo of N! % M
  int res = 1;
  for( int i = 1; i <= n; ++i ){
    res = 1LL * res * i % m;
  }
  return res % m;
}

int int_pow( int v, int p, int mod ){
  int res = 1;
  while( p ){
    if( p & 1 ){
      res = 1LL * res * v % mod;
    }
    p >>= 1;
    v = 1LL * v * v % mod;
  }
  return res;
}

int mod_inv( int v, int mod ){
  return int_pow( v, mod - 2, mod );
}

void solve(){
  int T; cin >> T;
  for( int kase = 0; kase < T; ++kase ){
    int N, M; cin >> N >> M;
    if( N >= M ){
      cout << 0 << endl;
    } else if( N <= ( int ) 2e5 ){
      cout << bruteforce( N, M ) << endl;
    } else if( is_prime( M ) ){
      // ( M - 1 ) ! % M == ( M - 1 )
      // N ! % M == ( M - 1 ) * ( ( M - 1 ) ! / N ! ) ^ ( -1 )
      // ^ ( -1 ) because M > N
      int ans = 1;
      for( int i = N + 1; i <= M - 1; ++i ){
        ans = 1LL * ans * i % M;
      }
      ans = 1LL * mod_inv( ans, M ) * ( M - 1 ) % M;
      cout << ans << endl;
    } else{
      if( N >= M / 2 ){
      cout << 0 << endl;
      } else{
        assert( M <= ( int ) 2e5 and N <= ( int ) 1e5 );
        cout << bruteforce( N, M ) << endl;
      }
    }
  }
}

signed main(){
  ios::sync_with_stdio( 0 );
  init();
  preprocess();
  solve();
  return 0;
}
0