zoukankan      html  css  js  c++  java
  • poj 3070 Fibonacci 矩阵快速幂

    题目链接:http://poj.org/problem?id=3070

    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).

    题意描述:菲波那契数列可以用题中那个矩阵计算得到,给出n(n可以超大),求出Fn。

    算法分析:赤果果的矩阵快速幂。如果对矩阵快速幂不熟悉的话,可以先百度看看讲解。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<cstdlib>
     5 #include<cmath>
     6 #include<algorithm>
     7 using namespace std;
     8 const int mod=10000;
     9 
    10 int n;
    11 struct matrix
    12 {
    13     int an[2][2];
    14 }res;
    15 matrix multiply(matrix a,matrix b)
    16 {
    17     matrix s;
    18     memset(s.an,0,sizeof(s.an));
    19     for (int i=0 ;i<2 ;i++)
    20     {
    21         for (int j=0 ;j<2 ;j++)
    22         {
    23             for (int k=0 ;k<2 ;k++)
    24             {
    25                 s.an[i][j] += a.an[i][k]*b.an[k][j];
    26                 if (s.an[i][j]>mod) s.an[i][j]%=mod;
    27             }
    28         }
    29     }
    30     return s;
    31 }
    32 void calc(int n)
    33 {
    34     matrix sum;
    35     for (int i=0 ;i<2 ;i++)
    36     {
    37         for (int j=0 ;j<2 ;j++)
    38         sum.an[i][j]= i==j ? 1 : 0 ;
    39     }
    40     for (int i=0 ;i<2 ;i++)
    41     {
    42         for (int j=0 ;j<2 ;j++)
    43         res.an[i][j]=1;
    44     }
    45     res.an[1][1]=0;
    46     while (n)
    47     {
    48         if (n&1) sum=multiply(sum,res);
    49         n >>= 1;
    50         res=multiply(res,res);
    51     }
    52     printf("%d
    ",sum.an[1][0]%mod);
    53 }
    54 
    55 int main()
    56 {
    57     while (scanf("%d",&n)!=EOF && n!=-1)
    58     {
    59         calc(n);
    60     }
    61     return 0;
    62 }
  • 相关阅读:
    Quartz cron表达式
    Apache NiFi 核心概念和关键特性
    Hive llap服务安装说明及测试(一)
    nifi生产环境使用
    DataX 中Transformer的使用
    vue2.0之过渡动画,分别用钩子函数,animated,原生css实现(前端网备份)
    js对对象数组的某一字段排序(前端网备份)
    浏览器之禁扒(前端网备份)
    iframe 从父像子穿参数(前端网备份)
    关于小程序仿微博导航效果(前端网备份 )
  • 原文地址:https://www.cnblogs.com/huangxf/p/4400942.html
Copyright © 2011-2022 走看看