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 }
     
  • 相关阅读:
    python web自动化测试框架搭建(功能&接口)——通用模块
    Python web自动化测试框架搭建(功能&接口)——unittest介绍
    什么是Referrer-Policy
    git pull 问题
    [坑]sed命令替换指定字符后不固定字符串,文本信息的替换删除
    修改Mysql procedure,function and view definer
    遵循PEP8风格指南
    Mysql create constraint foreign key faild.trouble shooting method share
    Spring JDBC FOUND_ROWS 安全吗?
    邮件安全产品方案
  • 原文地址:https://www.cnblogs.com/anhuizhiye/p/3688520.html
Copyright © 2011-2022 走看看