Poj 3070 Fibonacci (Rapid matrix power)

Source: Internet
Author: User

Address: poj 3070

With this question, I learned to use the matrix's fast power to quickly calculate the Fibonacci number.


According to the previous formula, the number of the 1st columns in the 2nd rows and the 2nd columns in the 1st rows is the nth Fibonacci number. Therefore, you can construct a matrix and evaluate the power.

The Code is as follows:

#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;const int mod=1e4;struct matrix{    int ma[3][3];}init, res;matrix Mult(matrix x, matrix y){    matrix tmp;    int i, j, k;    for(i=0;i<2;i++)    {        for(j=0;j<2;j++)        {            tmp.ma[i][j]=0;            for(k=0;k<2;k++)            {                tmp.ma[i][j]=(tmp.ma[i][j]+x.ma[i][k]*y.ma[k][j])%mod;            }        }    }    return tmp;}matrix Pow(matrix x, int k){    int i, j;    matrix tmp;    for(i=0;i<2;i++)    {        for(j=0;j<2;j++)        {            tmp.ma[i][j]=(i==j);        }    }    while(k)    {        if(k&1) tmp=Mult(tmp,x);        x=Mult(x,x);        k>>=1;    }    return tmp;}int main(){    int k;    while(scanf("%d",&k)!=EOF&&k>=0)    {        init.ma[0][0]=1;        init.ma[0][1]=1;        init.ma[1][0]=1;        init.ma[1][1]=0;        res=Pow(init,k);        printf("%d\n",res.ma[0][1]);    }    return 0;}


Poj 3070 Fibonacci (Rapid matrix power)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.