【矩阵快速幂-求平方根表达式的值】HDU Problem of Precision 2256



Problem of Precision

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1055    Accepted Submission(s): 622


Problem Description
【矩阵快速幂-求平方根表达式的值】HDU Problem of Precision 2256_第1张图片
 

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
 

Source
HDOJ 2008 Summer Exercise(4)- Buffet Dinner
 


题意:

简单明了。不再解释。

解题思路:

盗图。。这图讲的足够了。

【矩阵快速幂-求平方根表达式的值】HDU Problem of Precision 2256_第2张图片

矩阵:

AC代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
#define MOD 1024

using namespace std;

typedef int LL;

LL Mat[2][2];
LL res[2][2];

void init()
{
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){
            res[i][j]=(i==j);
        }
    }
    Mat[0][0]=5;Mat[0][1]=2;
    Mat[1][0]=12;Mat[1][1]=5;
}

void Matmul(LL a[2][2],LL b[2][2])
{
    LL t[2][2]={0};
    for(int i=0;i<2;i++){
        for(int k=0;k<2;k++){
            if(a[i][k]){
                for(int j=0;j<2;j++){
                   t[i][j]=(t[i][j]+a[i][k]*b[k][j]%MOD)%MOD;
                }
            }
        }
    }
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
            a[i][j]=t[i][j];
}

void Matrix(LL x[2][2],LL n)
{
    while(n){
        if(n&1) Matmul(res,x);
        Matmul(x,x);
        n>>=1;
    }
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        LL n;
        scanf("%d",&n);
        init();
        Matrix(Mat,n-1);
        LL ans[2];
        LL cnt=0;
        ans[0]=5;ans[1]=2;
        for(int i=0;i<2;i++){
            cnt=(cnt+ans[i]*res[i][0]%MOD)%MOD;
        }
        printf("%d\n",(2*cnt-1)%MOD);
    }
    return 0;
}


Problem of Precision

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1055    Accepted Submission(s): 622


Problem Description
【矩阵快速幂-求平方根表达式的值】HDU Problem of Precision 2256_第3张图片
 

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
 

Source
HDOJ 2008 Summer Exercise(4)- Buffet Dinner
 

你可能感兴趣的:(【矩阵快速幂-求平方根表达式的值】HDU Problem of Precision 2256)