题目链接:登录—专业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;
}