zoukankan      html  css  js  c++  java
  • poj_3070Fibonacci(矩阵快速幂)

    Fibonacci
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 12732   Accepted: 9060

    Description

    In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:

    0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

    An alternative formula for the Fibonacci sequence is

    .

    Given an integer n, your goal is to compute the last 4 digits of Fn.

    Input

    The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

    Output

    For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

    Sample Input

    0
    9
    999999999
    1000000000
    -1

    Sample Output

    0
    34
    626
    6875

    Hint

    As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

    .

    Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

    .

    Source

     
     1 //快速幂矩阵
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 using namespace std;
     6 struct Mat{
     7     int mat[2][2];
     8 };
     9 const int Mod = 10000;
    10 Mat operator *(Mat a, Mat b)
    11 {
    12     Mat c;
    13     memset(c.mat,0,sizeof(c.mat));
    14     for(int i = 0; i < 2; i++)
    15     {
    16         for(int j = 0; j < 2; j++)
    17         {
    18             for(int k = 0; k < 2; k++)
    19             {
    20                 c.mat[i][j] = (c.mat[i][j]+(a.mat[i][k]*b.mat[k][j])%Mod)%Mod;
    21             }
    22         }
    23     }
    24     return c;
    25 }
    26 Mat multi(int n)
    27 {
    28     Mat c;
    29     memset(c.mat,0,sizeof(c.mat));
    30     c.mat[0][0] = c.mat[1][1] = 1;
    31     Mat a;
    32     memset(a.mat,0,sizeof(a.mat));
    33     a.mat[0][0] = a.mat[0][1] = a.mat[1][0] = 1;
    34     while(n)
    35     {
    36         if(n&1) c = c*a;
    37         a = a*a;
    38         n>>=1;
    39     }
    40     return c;
    41 }
    42 int main()
    43 {
    44     int n;
    45     while(~scanf("%d",&n))
    46     {
    47         if(n==-1) return 0;
    48         Mat ans = multi(n);
    49         printf("%d
    ",ans.mat[0][1]);
    50     }
    51     return 0;
    52 }
  • 相关阅读:
    Python 小试牛刀
    Python 流程控制
    Python
    CMDB
    CMDB
    CMDB
    C#学习日志 day 2 plus ------ hyper-V 开启方法
    C#学习日志 day 2 ------ 控制台颜色以及windowsphone 窗体应用试建
    C#学习日志 day 1 ------ hello C# !
    wamp出现You don’t have permission to access/on this server提示(转)
  • 原文地址:https://www.cnblogs.com/shanyr/p/5672293.html
Copyright © 2011-2022 走看看