题目描述
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≤100,1≤n,q,p≤10 9
输出描述:
For each test case, you need to output a single line with the integer S.
示例1
输入
2
2 3 100
511 4 520
输出
14
184
思路
参考博客
这个ACM我是一道也不会。。。┭┮﹏┭┮
此题知识点
为啥要用这个公式呢,因为数太大了。。。
还有就是pow_m()求a的b次方的函数的方法需要记一下,别的方法运行超时
代码
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
ll pow_m(ll a,ll b,ll m){
ll res=1;
while(b)
{
if(b%2)
res=(res*a)%m;
a=(a*a)%m;
b/=2;
}
return res;
}
ll solve(ll q,ll n,ll p){
if(n==1) return q%p;
if(n%2==0) return (1+pow_m(q,n/2,p))*solve(q,n/2,p)%p;
else return ((1+pow_m(q,n/2,p))*solve(q,n/2,p)%p+pow_m(q,n,p))%p;
}
int main(){
int t;
cin>>t;
while(t--){
ll q,n,p;
cin>>q>>n>>p;
ll sum=solve(q,n,p);
cout<<sum<<endl;
}
return 0;
}