結果
| 問題 |
No.181 A↑↑N mod M
|
| コンテスト | |
| ユーザー |
yosupot
|
| 提出日時 | 2015-04-06 00:19:50 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 2,203 bytes |
| コンパイル時間 | 1,268 ms |
| コンパイル使用メモリ | 168,352 KB |
| 実行使用メモリ | 13,880 KB |
| 最終ジャッジ日時 | 2024-07-04 02:22:37 |
| 合計ジャッジ時間 | 7,690 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 TLE * 1 -- * 3 |
| other | -- * 37 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
// x^n % md
ll pow_mod(ll x, ll n, P md) {
ll y = 1;
for (int i = 0; i < n; i++) {
y *= x;
if (y > md.first) {
y -= md.first;
y %= md.second;
y += md.first;
}
}
return y;
/* ll r = 1;
while (n) {
if (n & 1) {
r = r * x;
if (r > md.first) {
r -= md.first;
r %= md.second;
r += md.first;
}
}
x = x * x;
if (x > md.first) {
x -= md.first;
x %= md.second;
x += md.first;
}
n >>= 1;
}
return r;*/
}
// x^n % md
ll pow_mod(ll x, ll n, ll md) {
ll r = 1;
while (n) {
if (n & 1) r = (r * x) % md;
x = (x * x) % md;
n >>= 1;
}
return r % md;
}
P cycle(ll a, ll m) {
ll x = 1;
map<ll, ll> mp;
mp[x] = 0;
for (int i = 1; i < 100000; i++) {
x *= a;
x %= m;
if (mp.count(x)) {
return {mp[x], i-mp[x]};
}
mp[x] = i;
}
assert(false);
}
int main() {
ll a, n, m;
cin >> a >> n >> m;
if (a == 1 || n == 0) {
cout << 1 % m << endl;
return 0;
}
if (m == 1) {
cout << 0 << endl;
return 0;
}
n--;
P p = cycle(a, m);
assert(p.second);
ll x = 1;
if (a < 10000) {
for (int i = 0; i < n; i++) {
x = pow_mod(a, x, p);
}
cout << pow_mod(a, x, m) << endl;
return 0;
}
assert(false);
map<ll, ll> mp;
mp[x] = 0;
bool f = false;
for (int i = 1; i < 100000; i++) {
x = pow_mod(a, x, p);
if (mp.count(x)) {
f = true;
if (n < mp[x]) break;
n -= mp[x];
n %= i - mp[x];
n += mp[x];
break;
}
mp[x] = i;
}
assert(f);
x = 1;
for (int i = 0; i < n; i++) {
x = pow_mod(a, x, p);
}
cout << pow_mod(a, x, m) << endl;
return 0;
}
yosupot