1.非递归的解法
#include <iostream>
using namespace std;
int main(){int a,b,c,t=1;cin>>a>>b>>c;if(a>=2&&a<=1e3&&b>=0&&a<=1e7&&c>=2&&c<=1e5)for(int i=0;i<b;i++)t=t*a%c;cout<<t;return 0;
}
2.递归写法:基于二分不断递归的思想,也称二分幂。
#include <iostream>
using namespace std;
typedef long long ll;
ll result1;
ll binary(int a,int b,int c){if(b==0) return 1;//对于奇数,不断--递归b次,相当于for循环if(b%2==1) return a*binary(a,b-1,c)%c;else{//对于偶数,不断递归二分为奇数,求出平方即可得原数ll mul=binary(a,b/2,c);return mul*mul%c;}
}
int main(){int a,b,c;cin>>a>>b>>c;if(a>=2&&a<=1e3&&b>=0&&a<=1e7&&c>=2&&c<=1e5)result1=binary(a,b,c);cout<<result1<<endl;return 0;
}