poj 3070 Fibonacci 矩阵相乘

Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 7715   Accepted: 5474

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

 
想学高斯消元,先学矩阵。
二分思想,在A^B mod m中已经体现..
 1 #include<iostream>

 2 #include<cstdio>

 3 #include<cstdlib>

 4 #include<cstring>

 5 

 6 struct node

 7 {

 8     int a[5][5];

 9 }now,cur;

10 

11 

12 void make_first()

13 {

14     now.a[1][1]=1;

15     now.a[1][2]=1;

16     now.a[2][1]=1;

17     now.a[2][2]=0;

18 

19     cur.a[1][1]=1;

20     cur.a[1][2]=1;

21     cur.a[2][1]=1;

22     cur.a[2][2]=0;

23 }

24 

25 struct node make_cheng(node  a,node b) //发现结构体忘记了。

26 {

27     struct node f;

28     int i,k,j;

29     memset(f.a,0,sizeof(f.a));

30     for(i=1;i<=2;i++)

31     for(k=1;k<=2;k++)

32     if(a.a[i][k])

33     {

34         for(j=1;j<=2;j++)

35         if(b.a[k][j])

36         {

37             f.a[i][j]+=a.a[i][k]*b.a[k][j];

38             if(f.a[i][j]>=10000)

39             f.a[i][j]%=10000;

40         }

41     }

42     return f;

43 }

44 

45 void make_EF(int n)

46 {

47     make_first();

48     while(n)

49     {

50         if(n&1)

51         {

52             now=make_cheng(now,cur);//!!!

53         }

54         n=n/2;

55         cur=make_cheng(cur,cur);

56     }

57     printf("%d\n",now.a[1][1]);

58 }

59 

60 int main()

61 {

62     int n;

63     while(scanf("%d",&n)>0)

64     {

65         if(n==-1)break;

66         if(n==0){printf("0\n");continue;}

67         if(n==1||n==2){printf("1\n");continue;}

68         make_EF(n-2);

69     }

70     return 0;

71 }

 

你可能感兴趣的:(fibonacci)