根据题意找出递推式子,利用矩阵快速幂求得即可,代码如下:
#include<bits/stdc++.h>
using namespace std;
using ll =long long;
const int M=1e9+7;
ll T;
struct m{
ll c[2][2];
m(){memset(c,0,sizeof c);}
};
m operator*(m &x,m &y){
m t;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
t.c[i][j]=(t.c[i][j]+x.c[i][k]*y.c[k][j])%M;
return t;
}
void solved()
{
ll n,k; cin>>n>>k;
ll f1=k;
ll f2=((k*k-2)%M+M)%M;
if(n==1) cout<<f1<<'\n';
else if(n==2) cout<<f2<<'\n';
else{
m x; x.c[0][0]=k; x.c[0][1]=-1; x.c[1][0]=1; x.c[1][1]=0;
m res;
for(int i=0;i<2;i++) res.c[i][i]=1;
ll su =n-2;
while(su)
{
if(su&1) res=res*x;
x=x*x;
su>>=1;
}
cout<<((res.c[0][0]*f2+res.c[0][1]*f1)%M+M)%M<<'\n';
}
}
int main()
{
cin>>T;
while(T--)
{
solved();
}
}