大数取模的二进制方法

2019-04-13 16:14发布

 我们先把b转化为2进制       b=(a[t] a[t-1] a[t-2]....a[1] a[0])   (a[i]为0或1) 那么b = a[t]*2^t + a[t-1]*2^(t-1) + ... ... + a[1]*2^1 + a[0]*2^0(其中 a[i]=0,1) a^b mod c =a^(a[t]*2^t + a[t-1]*2^(t-1) + ... ... + a[1]*2^1 + a[0]*2^0) mod c; = ((a^(a[0]*2^0) mod c) * a^(a[1]*2^1) mod c) ... ...       注意: a^(2^(i+1))mod c = (a^ (2^i) mod c)^2 mod c #include using namespace std; typedef long long int ll;; ll mod_exp(ll a, ll b_0, ll n) { if (a > n) a %= n; ll i, d = 1, b[70]; for (i = 0; i < 70; i++) { b[i] = b_0 % 2; b_0 /= 2; if(b_0 == 0) { break; } } for (; i >= 0; i--) { d = (d * d) % n; if (b[i] == 1) d = (d * a) % n; } return d; } int main() { std::ios::sync_with_stdio(false); ll m,n; ll b; while(std::cin>>m>>b>>n) cout<