码迷,mamicode.com
首页 > 其他好文 > 详细

清北模拟 求和

时间:2016-08-22 00:24:22      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

给定项数、公比、模数,求首项为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;
}

 

清北模拟 求和

标签:

原文地址:http://www.cnblogs.com/hyfer/p/5794052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!