zoukankan      html  css  js  c++  java
  • POJ ---3070 (矩阵乘法求Fibonacci 数列)

    Fibonacci
     

    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

    思路:矩阵快速幂,没什么可说的。

     1 #include<cstdio>
     2 #include<string>
     3 #include<cstring>
     4 #include<iostream>
     5 #include<algorithm>
     6 using namespace std;
     7 typedef struct Matrix{
     8     int m[2][2];
     9     Matrix(){
    10         memset(m, 0, sizeof(m));
    11     }
    12 }Matrix;
    13 Matrix mtMul(Matrix A, Matrix B){
    14     Matrix tmp;
    15     for(int i = 0;i < 2;i ++)
    16         for(int j = 0;j < 2;j ++)
    17             for(int k = 0;k < 2;k ++){
    18                 int t = (A.m[i][k] * B.m[k][j])%10000;
    19                 tmp.m[i][j] = (tmp.m[i][j] + t)%10000;  
    20             }
    21     return tmp;
    22 }
    23 Matrix mtPow(Matrix A, int k){
    24     if(k == 1) return A;
    25     Matrix tmp = mtPow(A, k >> 1);
    26     Matrix res = mtMul(tmp, tmp);
    27     if(k & 1) res = mtMul(res, A);
    28     return res;
    29 }
    30 int main(){
    31     int n;
    32     while(~scanf("%d", &n) && (n+1)){
    33         if(n == 0) printf("0
    ");
    34         else{
    35             Matrix M;
    36             M.m[0][0] = M.m[0][1] = M.m[1][0] = 1;
    37             M.m[1][1] = 0;
    38             Matrix tmp = mtPow(M, n);
    39             printf("%d
    ", tmp.m[1][0]);
    40         }
    41     }
    42     return 0;
    43 }
     
  • 相关阅读:
    转载--Linux命令top动态观察程序的变化
    转载--C语言运算符优先级和口诀
    区别typedef和#define
    spring+springmvc+mybatis xml配置文件
    解决SmartGit序列号问题
    通过SmartGit把java maven项目传到码云
    301跳转
    mybatis之联表查询
    MySQL不常用、易忽略的小知识
    JavaScript精进篇
  • 原文地址:https://www.cnblogs.com/anhuizhiye/p/3688520.html
Copyright © 2011-2022 走看看