Thursday, March 23, 2017

BigMod and BigsumMod

/*  Bismillahir Rahmanir Rahim
    BigMod of Series:
    (1 + b + b^2 + b^3 + b^4 +......+ b^(p-1) )%mod
*/

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll b, p, m;

ll bigmod(ll b, ll p, ll m){ // its the BigMod
    if(p==0) return 1;
    ll x=bigmod(b, p/2, m);
    x=(x*x)%m;
    if(p%2==1) x=(x*b)%m;
    return x;
}

ll bigsummod(ll b, ll p, ll m){ // mod in every line
    if(p==2) return (1+b)%m;  // when 2 term (1+b)
    else if(p==3) return (1+b+b*b)%m;
    else if(p%2==1) return (1+b*bigsummod(b, p-1, m))%m;
    else{
       ll xx=bigsummod(b, p/2, m)%m;
       return xx=(xx+(bigmod(b, p/2, m)*xx))%m;
    }
}

int main(){
    while(cin>>b>>p>>m){ // b=Base, p=power+1(number of term), m=mod
        cout<<bigsummod(b, p, m)<<endl;
    }
    return 0;
}

No comments:

Post a Comment