算法竞赛入门经典:第十章 数学概念与方法 10.5幂取模

/*
幂取模:
输入正整数a、n和m,输出a^n mod  m 的值,a, n , m <= 10^9

输入:
2 3 3
2 4 3
输出:
2
1
*/

/*
关键:
1 if(0 == n)//递归出口是n==1时,表示为1的数字,防止陷入n=0,n/2=0的无限递归之中
2 int x = powerMod(a,n/2,m);//这里采用递归,用n/2来缩小问题,起始是分治法,时间复杂度为O(log n)
3 long long ans = (long long)x * x % m;//这里ans由于涉及到long long,因此等式左边也需要用long long
4 return (int)ans;//最后由于除数<=10^9,因此最后的模只可能为int,因此需要将long long转换为int
*/

#include <stdio.h>

int powerMod(int a,int n,int m)
{
	if(0 == n)//递归出口是n==1时,表示为1的数字,防止陷入n=0,n/2=0的无限递归之中
	{
		return 1;
	}
	int x = powerMod(a,n/2,m);//这里采用递归,用n/2来缩小问题,起始是分治法,时间复杂度为O(log n)
	long long ans = (long long)x * x % m;//这里ans由于涉及到long long,因此等式左边也需要用long long
	if(n % 2 == 1)
	{
		ans = ans * a % m;
	}
	return (int)ans;//最后由于除数<=10^9,因此最后的模只可能为int,因此需要将long long转换为int
}



void process()
{
	int a,n,m;
	while(EOF != scanf("%d %d %d",&a,&n,&m))
	{
		printf("%d\n",powerMod(a,n,m));
	}
}

int main(int argc,char* argv[])
{
	process();
	getchar();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值