pell方程递推式!!!x^2-dy^2=1


递推式如上!

根据上式我们可以构造矩阵




通过矩阵快速幂,就可以快速求出第k大的解。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef  long long ll;
const int mod=8191;
struct matrix{ll a[2][2];matrix(){memset(a,0,sizeof(a));}};
matrix ans;
matrix multi(matrix a,matrix b)
{
    matrix ans;
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
            for(int k=0;k<2;k++)
                ans.a[i][j]=(ans.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;
    return ans;
}
matrix qpow(matrix res,ll k)
{
    while(k)
    {
        if(k&1)
            res=multi(res,ans);
        k/=2;
        ans=multi(ans,ans);
    }
    return res;
}
int main()
{
    ll n,k;
    while(scanf("%lld%lld",&n,&k)!=EOF)
    {
        ll nn=sqrt(n),keepx,keepy;
        if(nn*nn==n){printf("No answers can meet such conditions\n");continue;}
        for(int i=1;;i++){ll y=i*i*n+1;ll yy=sqrt(y);if(yy*yy==i*i*n+1){keepy=i;keepx=yy;break;}}
        ans.a[0][0]=keepx%mod;
        ans.a[0][1]=n*keepy%mod;
        ans.a[1][0]=keepy%mod;
        ans.a[1][1]=keepx%mod;
        matrix res;
        res.a[0][0]=1,res.a[1][1]=1;
        matrix ans=qpow(res,k-1);
        printf("%lld\n",(ans.a[0][0]*keepx%mod+ans.a[0][1]*keepy%mod+mod)%mod);
    }
    return 0;
}





你可能感兴趣的:(数学-矩阵)