B.Icebound and Sequence

博客围绕链接https://ac.nowcoder.com/acm/contest/903/B的题目展开,题目要求根据给定的q、n、p计算S=(∑ni=1qi) mod p的值。解题思路是采用等比数列求和,考虑取余不能直接计算,分n为偶数和奇数两种情况给出求和公式,代码转载自https://www.cnblogs.com/YDDDD/p/10923486.html。

链接:https://ac.nowcoder.com/acm/contest/903/B

题意:

Icebound hates math. But Imp loves math. One day, Imp gave icebound a problem.

The problem is as follows.

S=(ni=1qi mod pS=(∑i=1nqi) mod p

For given q,n,p, you need to help icebound to calculate the value of S.

思路:

等比数列求和。

因为考虑到取余,所以不能直接算。

令S(n) 为等比数列前n项和。

若n为偶数:

  S(n) = S(n/2) + S(n/2)*a^(n/2) (因为第i(i <= n/2)项和i+n/2项存在第i项乘a^(n/2)等以第i+n/2项的值。

若n为奇数:

  S(n) = S(n/2) + S(n/2)*a^(n/2) + a^n

代码:

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;

LL n, q, p;

LL QM(LL a, LL b, LL m)
{
    LL res = 1;
    while (b)
    {
        if (b&1)
            res = (res*a)%m;
        a = (a*a)%m;
        b >>= 1;
    }
    return res;
}

LL GetR(int t)
{
    if (t == 1)
        return n%p;
    if (t%2 == 0)
        return (GetR(t/2)+(GetR(t/2)*QM(n, t/2, p))%p)%p;
    else
        return ((GetR(t/2)+(GetR(t/2)*QM(n, t/2, p))%p)%p+QM(n, t, p))%p;
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        cin >> n >> q >> p;
        cout << GetR(q) << endl;
    }

    return 0;
}

  

转载于:https://www.cnblogs.com/YDDDD/p/10923486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值