快速幂取模 分类: ACM TYPE 2014-08-29 22:01 95人阅读 评论(0) 收藏

时间:2023-11-28 10:57:32
#include<stdio.h>
#include<stdlib.h>
//快速幂算法,数论二分
long long powermod(int a,int b, int c) //不用longlong就报错,题目中那个取值范围不就在2的31次方内
{
long long t;
if(b==0) return 1%c;
if(b==1) return a%c;
t=powermod(a,b/2,c);//递归调用,采用二分递归算法,,注意这里n/2会带来奇偶性问题
t=t*t%c;//二分,乘上另一半再求模
if(b&1) t=t*a%c;//n是奇数,因为n/2还少乘了一次a
return t;
}
int main()
{
int n;
long long a,b,c;
scanf("%d",&n);
while(n--)
{
scanf("%lld%lld%lld",&a,&b,&c);
printf("%lld\n",powermod(a,b,c));
}
return 0;
}

Code From Nyoj 102

版权声明:本文为博主原创文章,未经博主允许不得转载。