等比数列二分法求和

#include <iostream>
#include <cstdio> 
#define ll long long
using namespace std;

ll pow_mod(ll a, ll b, ll mod) {
    ll ans = 1;
    a %= mod;
    while (b) {
        if (b & 1) {
            ans = ans * a % mod;
        }
        a = a * a % mod;
        b >>= 1;
    }
    return ans;
}
ll sum(ll a, ll n,ll M)
{
    if (n == 1) return a;
    ll t = sum(a, n / 2,M);
    if (n & 1)
    {
        ll cur = pow_mod(a, n / 2 + 1,M);
        t = (t + t * cur % M) % M;
        t = (t + cur) % M;
    }
    else
    {
        ll cur = pow_mod(a, n / 2,M);
        t = (t + t * cur % M) % M;
    }
    return t;
}

int main()
{
    ll a, n,M;
    int T;
    cin >> T;
    while (T--) {
        cin >> a >> n >> M;
        cout << sum(a, n,M)<< endl;
    }
    return 0;
}

 

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务