Problem Description
There’s an array that is generated by following rule.
h0=2,h1=3,h2=6,hn=4hn−1+17hn−2−12hn−3−16
And let us define two arrays bnandan as below.
bn=3hn+1hn+9hn+1hn−1+9h2n+27hnhn−1−18hn+1−126hn−81hn−1+192(n>0)
an=bn+4n
Now, you have to print ⌊√(an)⌋ , n>1.
Your answer could be very large so print the answer modular 1000000007.
h0=2,h1=3,h2=6,hn=4hn−1+17hn−2−12hn−3−16
And let us define two arrays bnandan as below.
bn=3hn+1hn+9hn+1hn−1+9h2n+27hnhn−1−18hn+1−126hn−81hn−1+192(n>0)
an=bn+4n
Now, you have to print ⌊√(an)⌋ , n>1.
Your answer could be very large so print the answer modular 1000000007.
Input
The first line of input contains T (1 <= T <= 1000) , the number of test cases.
Each test case contains one integer n (1 < n <= 1015) in one line.
Each test case contains one integer n (1 < n <= 1015) in one line.
Output
For each test case print ⌊√(a_n )⌋ modular 1000000007.
Sample Input
Sample Output
3 4 7 9
1255 324725 13185773
2017年多校第十场的题,当时做的时候看到数据范围和对1e9+7取余很容易想到是矩阵快速幂。
暴力写了前几项,发现分别是31,197,1255,7997,50959
发现:
7*197-4*31=1255
7*1255-4*197=7997
7*7997-4*1255=50959
于是递推式很容易看出来了了
√an=7*√an-1-4*√an-2
写一个2*2的矩阵即可
如果猜的和h(n)公式一样,那么需要写一个3*3的矩阵
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<map>
#include<algorithm>
#include<iostream>
#define ll long long
#define ull unsigned long long
const int N=1e9+7;
const int M=1e6+5;
using namespace std;
struct node
{
ll jz[2][2];
} d,e;
node cf(node a,node b) //矩阵乘法
{
node c;
int i,j,k;
memset(c.jz,0,sizeof(c.jz));
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
for(k=0; k<2; k++)
{
c.jz[i][j]+=(a.jz[i][k]*b.jz[k][j]);
c.jz[i][j]%=N;
}
}
}
return c;
}
ll ksm(ll x) //矩阵快速幂
{
if(x==2) return 31;
if(x==3) return 197;
memset(d.jz,0,sizeof(d.jz));
for(int i=0; i<2; i++)
{
d.jz[i][i]=1;
}
e.jz[0][0]=7,e.jz[0][1]=-4;
e.jz[1][0]=1,e.jz[1][1]=0,
x-=3;
while(x)
{
if(x&1) d=cf(d,e);
e=cf(e,e);
x>>=1;
}
ll sum=197*d.jz[0][0]%N+31*d.jz[0][1]%N;
sum=(sum%N+N)%N;
return sum;
}
int main()
{
int T;
scanf("%d",&T);
ll n;
while(T--)
{
scanf("%I64d",&n);
printf("%I64d\n",ksm(n));
}
return 0;
}