結果
問題 | No.181 A↑↑N mod M |
ユーザー |
![]() |
提出日時 | 2015-08-02 08:20:28 |
言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
結果 |
AC
|
実行時間 | 2 ms / 5,000 ms |
コード長 | 1,747 bytes |
コンパイル時間 | 825 ms |
コンパイル使用メモリ | 77,008 KB |
実行使用メモリ | 5,248 KB |
最終ジャッジ日時 | 2024-11-24 03:22:56 |
合計ジャッジ時間 | 2,147 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 6 |
other | AC * 37 |
ソースコード
#include <iostream> #include <vector> #include <cstdio> #include <sstream> #include <map> #include <string> #include <algorithm> #include <queue> #include <cmath> #include <set> using namespace std; long long mypow(long long x, long long y, long long MOD){ if(x==0 && y!=0) return 0; long long ret=1LL; while(y>0LL){ if(y&1LL) ret = (ret * x) % MOD; x = (x*x) % MOD; y >>= 1LL; } return ret; } pair<int,int> func(long long A, long long M){ int u=0,v=0; vector<int> memo(M+1, -1); for(long long i=0, val=1; i<M; i++, val=val*A%M){ if(memo[val] >= 0){ u = memo[val]; v = i - memo[val]; break; } memo[val] = i; } return {u,v}; } // A^A^A...^A > u bool greater__(long long A, long long N, long long u){ if(u==0) return true; if(A==1) return A > u; double val = 1; for(int i=0; i<N; i++){ if(val>u) return true; val = pow(1.0*A, val); } return false; } long long tetoration(long long A, long long N){ long long ret = 1; while(N){ ret = mypow(A, ret, 1LL<<50); N--; } return ret; } long long dfs(long long A, long long N, long long u, long long M){ if(A==0) return 0; if(N==0){ return 1%M; } if(M==1){ return 0; } if(A%M == 0){ return 0; } auto x = func(A,M); bool g = greater__(A,N-1, x.first); if(g==false){ return mypow(A, tetoration(A,N-1) , M); } long long ret = dfs(A, N-1, x.first, x.second) - x.first + x.second*1000; ret = mypow(A, ret, M); ret = ret * mypow(A, x.first, M) % M; return ret%M; } int main(){ long long A,N,M; cin >> A >> N >> M; if(M==1){ cout << 0 << endl; return 0; } if(N==0){ cout << 1 << endl; return 0; } if(A==1){ cout << 1 << endl; return 0; } long long ans = dfs(A, N, 0, M); cout << ans << endl; return 0; }