結果
| 問題 | No.109 N! mod M |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2016-10-18 19:58:39 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.89.0) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,059 bytes |
| 記録 | |
| コンパイル時間 | 893 ms |
| コンパイル使用メモリ | 81,432 KB |
| 実行使用メモリ | 10,024 KB |
| 最終ジャッジ日時 | 2024-11-22 12:39:55 |
| 合計ジャッジ時間 | 23,074 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 1 WA * 5 TLE * 3 |
ソースコード
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))
#define repeat_from(i,m,n) for (int i = (m); (i) < (n); ++(i))
typedef long long ll;
using namespace std;
vector<int> sieve_of_eratosthenes(int n) { // enumerate primes in [2,n] with O(n log log n)
vector<bool> is_prime(n+1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i*i <= n; ++i)
if (is_prime[i])
for (int k = i+i; k <= n; k += i)
is_prime[k] = false;
vector<int> primes;
for (int i = 2; i <= n; ++i)
if (is_prime[i])
primes.push_back(i);
return primes;
}
vector<ll> factors(ll n, vector<int> const & primes) {
vector<ll> result;
for (int p : primes) {
if (n < p *(ll) p) break;
while (n % p == 0) {
result.push_back(p);
n /= p;
}
}
if (n != 1) result.push_back(n);
return result;
}
ll powi(ll x, ll y, ll p) { // O(log y)
assert (y >= 0);
x = (x % p + p) % p;
ll z = 1;
for (ll i = 1; i <= y; i <<= 1) {
if (y & i) z = z * x % p;
x = x * x % p;
}
return z;
}
ll inv(ll x, ll p) { // p must be a prime, O(log p)
assert ((x % p + p) % p != 0);
return powi(x, p-2, p);
}
int main() {
const vector<int> primes = sieve_of_eratosthenes(sqrt(1e9) + 3);
int t; cin >> t;
while (t --) {
ll n, m; cin >> n >> m;
assert (0 <= n and n <= 1e9);
assert (1 <= m and m <= 1e9);
assert (m <= n + 1e5);
vector<ll> ps = factors(m, primes);
ll ans;
if (ps.empty()) {
ans = 0;
} else if (ps.size() == 1) {
ans = m - 1;
repeat_from (i,n+1,m) {
ans = ans * inv(i, m) % m;
}
} else {
ans = 1;
repeat_from (i,1,n+1) {
ans = ans * (i+1) % m;
if (ans == 0) break;
}
}
cout << ans << endl;
}
return 0;
}