HDU 2256Problem of Precision(矩陣快速冪)

自為風月馬前卒發表於2018-09-12

題意

求$(sqrt{2} + sqrt{3})^{2n} pmod {1024}$

$n leqslant 10^9$

Sol

看到題解的第一感受:這玩意兒也能矩陣快速冪???

是的,它能qwq。。。。

首先我們把$2$的冪乘進去,變成了

$(5 + 2sqrt{6})^n$

設$f(n) = A_n + sqrt{6} B_n$

那麼$f(n+1) = (A_n + sqrt{6} B_n ) * (5 + 2sqrt{6})$

乘出來得到

$A_{n + 1} = 5 A_n + 12 B_n$

$B_{n + 1} = 2A_n + B B_n$

那麼不難得到轉移矩陣

$$egin{pmatrix} 5 & 12 \ 2 & 5 end{pmatrix}$$

這樣好像就能做了。。

但是實際上後我們最終會得到一個類似於$A_n + sqrt{6}B_n$的東西,這玩意兒還是不能取模

考慮如何把$sqrt{6}$的影響消掉。

$(5 + 2 sqrt{6})^n = A_n + sqrt{6}B_n$

$(5 – 2 sqrt{6})^n = A_n – sqrt{6}B_n$

相加得

$(5 + 2 sqrt{6})^n + (5 – 2 sqrt{6})^n = 2A_n$

考慮到$0 < (5 – 2sqrt{6})^n < 1$

那麼

$$lfloor (5 + 2sqrt{6})^n
floor = 2A_n – 1$$

做完啦qwq

 

#include<cstdio>
#include<cstring>
#include<iostream>
#define Pair pair<int, int> 
#define MP(x, y)
#define fi first
#define se second 
// #include<map>
using namespace std;
#define LL long long
const LL MAXN = 101, mod = 1024;
inline LL read() {
    char c = getchar(); LL x = 0, f = 1;
    while(c < `0` || c > `9`) {if(c == `-`) f = -1; c = getchar();}
    while(c >= `0` && c <= `9`) x = x * 10 + c - `0`, c = getchar();
    return x * f;
}
int T, N;
struct Matrix {
    LL m[5][5], N;
    Matrix() {N = 2; memset(m, 0, sizeof(m));}
    Matrix operator * (const Matrix &rhs) const {
        Matrix ans;
        for(int k = 1; k <= N; k++) 
            for(int i = 1; i <= N; i++)
                for(int j = 1; j <= N; j++)
                    (ans.m[i][j] += 1ll * m[i][k] * rhs.m[k][j] % mod) % mod;
        return ans;
    }
};

Matrix fp(Matrix a, int p) {
    Matrix base; base.m[1][1] = 1; base.m[2][2] = 1;
    while(p) {
        if(p & 1) base = base * a; 
        a = a * a; p >>= 1;
    }
    return base;
}
int main() {
    T = read();
    while(T--) {
        N = read();
        Matrix a; 
        a.m[1][1] = 5; a.m[1][2] = 12;
        a.m[2][1] = 2; a.m[2][2] = 5;
        a = fp(a, N - 1);
        LL ans = (5 * a.m[1][1] + 2 * a.m[1][2]) % mod;
        printf("%I64d
", (2 * ans - 1) % mod);
    }
    return 0;
}

/**/

相關文章