PTA- 7-87 计算N^N (20分)--快速幂取模

7-87 计算N^N (20分)

给出一个整数N,输出N^N(N的N次方)的十进制表示的值,如果这个值超过了214748364,就求结果对214748364的余数。

输入格式:
一个整数T,代表输入数据组数。接下来T行每行一个整数N(1 <= N <= 10^9)。

输出格式:
输出N^N对214748364的余数

输入样例:
2
2
3

输出样例:
4
27

思路
主要利用快速幂取模的方法,详见代码函数

#include<bits/stdc++.h>
#define p 214748364
using namespace std;
typedef long long LL;

LL fast(LL a, LL b){
	if(b==1) return a%p;
	LL ans = fast(a, b/2);
	ans = ans * ans % p;
	if(b&1) ans = ans * a % p;
	return ans;
}

int main()
{
	int n, t, ans;
	cin >> t; 
	while(t--){
		cin >> n;
		ans = fast(n, n);
		cout << ans << endl;
	}
	return 0;
}

欢迎大家批评改正,提提意见,让我们共同进步,加油!!!

发布了39 篇原创文章 · 获赞 2 · 访问量 3436

猜你喜欢

转载自blog.csdn.net/weixin_43581819/article/details/103916129