Sicily 1863. Elegant Fibonacci numbers again (Fibonacci + matrix power)

Source: Internet
Author: User

Question:

Fibonacci series, F [0] = 0, F [1] = 1, F [N] = f [N-2] + F [n-1], n> 1

Given N (0 <= n <2 ^ 32) and M, evaluate f [N] mod m.

 

Solution:

N is too large, so we cannot use the cyclic recursive Calculation of O (n ).

 

Conclusion: For matrices | 1 1 |, and matrices | Fn Fn-1 |, after the two are multiplied to obtain a new matrix | Fn + 1FN|, FN indicates the nth Number of fiber ACCI

         | 1 0 |     | Fn-1 Fn-2 |              | Fn  Fn-1

 

Therefore, we can use the rapid power modulo + matrix multiplication of O (logn) to calculate f [N].

Fast Power Process: A ^ B =

1, B = 0

A, B = 1

A ^ (B/2) * A ^ (B/2), B is even

A * a ^ (b-1), B is odd



#include<iostream>#include<cstdio>using namespace std;struct Node{    int arr[2][2];}o;Node MUL(Node a, Node b,const int &m){    Node tmp;    tmp.arr[0][0] = (a.arr[0][0]*b.arr[0][0] + a.arr[0][1]*b.arr[1][0]) % m;    tmp.arr[0][1] = (a.arr[0][0]*b.arr[0][1] + a.arr[0][1]*b.arr[1][1]) % m;    tmp.arr[1][0] = (a.arr[1][0]*b.arr[0][0] + a.arr[1][1]*b.arr[1][0]) % m;    tmp.arr[1][1] = (a.arr[1][0]*b.arr[0][1] + a.arr[1][1]*b.arr[1][1]) % m;    return tmp;}Node exp(Node mat, int n, const int &m){    if(n == 1) return o;        if(n & 1)    {        return MUL(o, exp(mat,n-1,m), m);    }    else    {        Node tmp = exp(mat,n>>1, m);        return MUL(tmp,tmp,m);    }}int main(){    o.arr[0][0] = o.arr[0][1] = o.arr[1][0] = 1; o.arr[1][1] = 0;    int cas;    scanf("%d",&cas);    while(cas --)    {        int n,m;        scanf("%d%d",&n,&m);        if(n == 0)        {            printf("0\n");            continue;        }                Node f = o;        f = exp(f,n,m);                printf("%d\n",f.arr[0][1] % m);    }}                                 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.