#include<iostream> using namespace std; int main(){ long long b,p,k,i,a,c; cin >> b >> p >> k; a=b; c= p; long long s=1; while(p>0){ if(p%2 == 1){ s = s * b % k; } b = b * b % k; p = p / 2; } cout<<a<<"^"<<c<<" "<<"mod"<<" "<<k<<"="<<s%k; }
一开始想到的是直接递归,一直二分递归,没有理解快速幂的思想,60分,超时了
#include<iostream> using namespace std; long long mod(long long a,long long b, long long c); int main(){ long long b,p,k,i; cin >> b >> p >> k; long long s = mod(b,p,k); cout<<b<<"^"<<p<<" "<<"mod"<<" "<<k<<"="<<s; } long long mod(long long a,long long b, long long c){ int ans; if(b == 1) return a % c; return (mod(a, b/2, c) % c)* (mod(a, b - b/2, c) % c) % c; }