http://poj.org/problem?id=3070

方法:
divide and conquer,类似于求幂
矩阵求幂
复杂度:O(logn)

| F(n+1) F(n)   | = | 1  1 |^n
| F(n)   F(n-1) |   | 1  0 |

 

注意:
矩阵的0次幂是单位矩阵

 

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

【原】 POJ 3070 Fibonacci 斐波那契数列 解题报告.

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

 

#include <stdio.h>
   2:  
struct Matrix
   4: {
int d=0 ):a11(a),a12(b),a21(c),a22(d){}
int d=0 ){a11=a;a12=b;a21=c;a22=d;}
int a22;
   8: };
   9:  
  10: Matrix MatrixMultiply( Matrix& a, Matrix& b )
  11: {
  12:     Matrix result ;
  13:     result.a11 = ( a.a11*b.a11 + a.a12*b.a21 ) % 10000 ;
  14:     result.a12 = ( a.a11*b.a12 + a.a12*b.a22 ) % 10000 ;
  15:     result.a21 = ( a.a21*b.a11 + a.a22*b.a21 ) % 10000 ;
  16:     result.a22 = ( a.a21*b.a12 + a.a22*b.a22 ) % 10000 ;
  17:  
return result ;
  19: }
  20:  
int n )
  22: {
  23:     Matrix result ;
if( n==0 )
  25:     {
  26:         result.set(1,0,0,1) ;
return result ;
  28:     }
if( n==1 )
return result ;
  31:     
  32:     Matrix tmp ;
  33:     tmp = Fibonacci( a, n/2 ) ;
  34:     result = MatrixMultiply( tmp, tmp ) ;
if( n%2==0 )
return result;
else
return MatrixMultiply(a,result) ;
  39: }
  40:  
void run3070()
  42: {
  43:     Matrix a,result ;
int n ;
  45:  
, &n ) && n!=-1 )
  47:     {
  48:         result = Fibonacci( a, n ) ;
, result.a12 ) ;
  50:     }
  51: }

相关文章:

  • 2021-08-07
  • 2021-12-03
  • 2021-08-13
  • 2021-11-25
  • 2021-11-09
  • 2022-12-23
  • 2021-12-05
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-15
  • 2021-12-15
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
  • 2021-12-05
相关资源
相似解决方案