Icebound and Sequence(等比数列公式的递归处理)

题目链接:登录—专业IT笔试面试备考平台_牛客网

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

The problem is as follows.



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

输入描述:

The first line contains an integer T, denoting the number of test cases.
The next T lines, each line contains three integers q,n,p, separated by spaces.
1≤T≤1001≤T≤100, 1≤n,q,p≤109

输出描述:

For each test case, you need to output a single line with the integer S.

示例:

输入:

2
2 3 100
511 4 520

输出:

14
184

高中知识学不好,连老本都吃不了  ╮(๑•́ ₃•̀๑)╭、

那么,首先让我来回顾一下高中关于等比数列的一个公式(当n为奇数时。。。当n为偶数时。。。)

现在看看,这个公式简直深得二分法的真谛!!!

所以,这道题的解决方法就是 快速幂+公式二分! 。:.゚ヽ(。◕‿◕。)ノ゚.:。+゚  。:.゚ヽ(。◕‿◕。)ノ゚.:。+゚  。:.゚ヽ(。◕‿◕。)ノ゚.:。+゚

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int t;
ll n,q,p;
 
ll qpow(ll q,ll n)//快速幂版子来一波
{
    ll res=1;
    while(n){
        if(n&1) res=res*q%p;
        q=q*q%p;
        n=n/2;
    }
    return res;
} 
 
ll dengb(ll n)//公式套一波 
{
    if(n==1) return q;
    if(n&1)//当n为奇数时 
	{
        return ( dengb((n-1)/2)*(1+qpow(q,(n+1)/2))%p+qpow(q,(n+1)/2))%p;
    }
	else//当n为偶数时 
	{
        return ( dengb(n/2)*( 1+qpow(q,n/2) )%p );
    }
}
int main(){
    cin>>t;
    while(t--){
        cin>>q>>n>>p;
        if(q==1){
            cout<<n<<"\n";
        }
        else cout<<dengb(n)<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值