hdu 2256

Problem of Precision

     Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


Problem Description

 

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
 

解题思路:这道题目完全没思路,看了别人的解题报告感觉还是似懂非懂。。

题目要求 (sqrt(2)+sqrt(3))的 2^n并%1024,要求出值来并不难,构造矩阵即可,但是要mod1024就有问题了,小数不能直接mod,但是如果你取整之后再mod,结果绝逼出问题,因为浮点数的精度问题。

求出来后,直接用(int)(Xn+Yn*sqrt(6))%1024,又会出问题,还是浮点数取整问题。看来在mod的时候有浮点数要格外注意,直接处理的话,不管怎么取整,都会出问题。

所以分割线下面的推算就避开了这个问题,这个确实好难想到,通过变换一下,得到最终的结果必定是2Xn-(0.101...)^n,因为最终mod是用不大于浮点数的最大整数在mod,所以最终结果就是2Xn-1.第二条确实好难想到!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
struct Mat{
 int mat[2][2];
};
Mat E,a;
Mat operator *(Mat a,Mat b)
{
    Mat c;
    memset(c.mat,0,sizeof (Mat));
    for(int i=0;i<2;i++)
        for (int j=0;j<2;j++)
        for (int k=0;k<2;k++)
    {
        if (a.mat[i][k]>0 && b.mat[k][j]>0)
        c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
        c.mat[i][j]%=1024;
    }
    return c;
}
Mat operator ^(Mat ac,int x)
{
    Mat c;
    c=E;
    for (;x;x>>=1)
    {
        if (x&1)
            c=c*ac;
        ac=ac*ac;
    }
    return c;

}
void init()
{
    memset(E.mat,0,sizeof (Mat));
    a.mat[0][0]=5;
    a.mat[0][1]=12;
    a.mat[1][0]=2;
    a.mat[1][1]=5;
    for (int i=0;i<2;i++)
        E.mat[i][i]=1;
}
int main()
{
    init();
    int t;
    scanf("%d",&t);
    while (t--)
    {
        int n;
        scanf("%d",&n);
        Mat s=a^(n-1);
        int q1=s.mat[0][0]*5+s.mat[0][1]*2;
        int ans=(q1*2-1)%1024;
        printf("%d\n",ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值