清北学堂模拟赛 求和

给定项数、公比、模数,求首项为1的等比数列的和

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
#define ll long long
using namespace std;
ll n,k,p;
ll sum,numa,numb;
ll euler_phi(ll x){
    ll m = (int)sqrt(x+0.5);
    ll ans = x;
    for(int i = 2;i <= m;i++){
        if(x % i == 0){
            ans = ans / i * (i-1);
            while(x % i == 0) x /= i;
        }
    }
    if(x > 1) ans = ans / x * (x-1);
    return ans;
}
ll q_mul(ll a,ll b,ll mod){
    ll ans = 0;
    while(b){
        if(b&1){
            b--;
            ans = (ans + a) % mod;
        }
        b/=2;
        a = (a + a) % mod;
    }
    return ans;
}
ll q_pow(ll a,ll b,ll mod){
    ll ans = 1;
    while(b){
        if(b&1){
            ans = q_mul(ans,a,mod);
        }
        b/=2;
        a = q_mul(a,a,mod);
    }
    return ans;
}
ll inv(ll a,ll n){
    return q_pow(a,euler_phi(n)-1,n);
}
int main(){
    //freopen("sunshine.in","r",stdin);
    //freopen("sunshine.out","w",stdout);
    cin>>n>>k>>p;
    numa = (q_pow(k,n,p) + p - 1) % p;
    numb = inv(k-1,p);
    sum = q_mul(numa,numb,p);
    cout<<sum;
    return 0;
}

 

posted @ 2016-08-21 23:58  ACforever  阅读(219)  评论(0编辑  收藏  举报