hdu-2256(矩阵快速幂+推导)

问题描述:

一句话题目:让你求(sqrt(2)+sqrt(3))^(2*n) mod 1024.

Input

The first line of input gives the number of cases, T. T test cases follow, each on a separate line. Each test case contains one positive integer n. (1 <= n <= 10^9) 

Output

For each input case, you should output the answer in one line.

Sample Input

3
1
2
5
Sample Output

9
97
841

题目分析:

先给出一个大佬的博客,自己太鶸了,这个公式和一开始的想法完全不一样,后来发现我最初的想法是错的(千万别想着用double 取模)

点击打开链接


然后就可以根据那个矩阵来写代码了。

代码如下:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;

const int mod=1024;
struct matrix//构建矩阵
{
    int f[3][3];
    matrix operator* (const matrix &a) const {
        matrix res;
        for (int i=1;i<=2;i++) {
            for (int j=1;j<=2;j++) {
                res.f[i][j]=0;
                for (int k=1;k<=2;k++)
                    res.f[i][j]=(res.f[i][j]+(*this).f[i][k]*a.f[k][j])%mod;
            }
        }
        return res;
    }
}a,b;

void init()//预处理矩阵
{
    b.f[1][1]=5,b.f[1][2]=12;
    b.f[2][1]=2,b.f[2][2]=5;
    a.f[1][1]=5;
    a.f[2][1]=2;
}

matrix fast_pow(matrix base,int k)//快速幂
{
    matrix ans=base;
    while (k) {
        if (k&1)
            ans=base*ans;
        base=base*base;
        k>>=1;
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    while (t--) {
        int n;
        scanf("%d",&n);
        if (n==1) { printf("%d\n",9); continue;}
        n-=2;
        init();
        struct matrix cur,ans;
        cur=b;
        cur=fast_pow(cur,n);
        ans=cur*a;
        printf("%d\n",(2*ans.f[1][1]-1)%mod);
    }
    return 0;
}





















  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值