快速幂变形(快速幂取模),同余定理

在一些计算中,数字可能过大,因此,我们可以使用同余定理对程序进行优化

同余定理,多个数字对同一个数字取余后的计算与计算后再取余同一个数字结果相同,在大量的数学计算规律中都可以实现;

快速幂取模:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int P(int a, int n, int c)
{
	if(n == 0)
		return 1;
	if(n == 1)
		return a % c;
	int k = P(a, n / 2, c) % c;
	if(n % 2 == 0)
		return k * k % c;
	else
		return k * k * a % c;
	
}

int main()
{
	int a, n, c;
	while(~scanf("%d%d%d", &a, &n, &c))
		printf("%d\n", P(a, n, c));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/someone_and_anyone/article/details/80956939
今日推荐