結果

問題 No.181 A↑↑N mod M
ユーザー koyumeishikoyumeishi
提出日時 2015-08-02 07:34:27
言語 C++11
(gcc 11.4.0)
結果
RE  
実行時間 -
コード長 1,607 bytes
コンパイル時間 2,249 ms
コンパイル使用メモリ 76,488 KB
実行使用メモリ 814,532 KB
最終ジャッジ日時 2023-09-25 00:30:30
合計ジャッジ時間 3,427 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 RE -
testcase_07 AC 1 ms
4,380 KB
testcase_08 MLE -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
testcase_30 -- -
testcase_31 -- -
testcase_32 -- -
testcase_33 -- -
testcase_34 -- -
testcase_35 -- -
testcase_36 -- -
testcase_37 -- -
testcase_38 -- -
testcase_39 -- -
testcase_40 -- -
testcase_41 -- -
testcase_42 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#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 gcd(long long a, long long b){
	if(b==0) return a;
	return gcd(b, a%b);
}


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<long long> 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*A, val);
	}
	return false;

}

long long dfs(long long A, long long N, long long u, long long M){
	if(N==0){
		return 1%M;
	}
	if(M==1){
		return 0;
	}
	auto x = func(A,M);
	bool g = greater__(A,N, x.first);
	if(g==false){
		return mypow(A, N, M);
	}

	long long ret = dfs(A, N-1, x.first, x.second);
	ret = mypow(A, ret, M);
	ret = (ret-u+M)%M * mypow(A, x.first, M) % M;
	return ret;
}

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;
}
0