• 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 }
  • 相关阅读:
    Discuz利用百度ping把我们网站自动提交到百度
    正则表达式速查表1
    thinkphp 新浪新闻采集代码演示
    php采集一网站的精美图片
    百度知道的php爬虫
    新浪新闻采集程序
    mysql pid文件丢失解决办法
    js位运算-按位非
    mysql表损坏解决方案
    h5新API之WebStorage解决页面数据通信问题
  • 原文地址:https://www.cnblogs.com/shanyr/p/5672293.html
Copyright © 2020-2023  润新知