bit 1047 Fibonacci Numbers

来源:互联网 发布:电机控制算法工程师 编辑:程序博客网 时间:2024/06/04 00:56

Fibonacci Numbers

时间限制: 1秒  内存限制: 64M

ProblemDescription

The Fibonacci sequence is the sequence of numbers such that everyelement is equal to the sum of the two previous elements, except for the firsttwo elements f[0] and f[1] which are respectively zero and one.


What is the numerical value of the f[n]? Because the number may be very huge,you just need to output the f[n] mod p.

Input

There are multiply test cases. Each test case, there is one linecontains two integers n and p (0 <= n <= 10^9, 1 <= p <= 10^9).

Output

For each test case, output an integer, denotes the result of f[n]mod p.

Sample Input

0 9997

1 9997

2 9997 

Sample Output

0

1



构造矩阵 进行快速幂

  f[n]                      1              1         f[n-1]

                    =                               *

  f[n-1]                  1               0         f[n-2]


#include <stdio.h>long long int base[2][2]= {{1,1},{1,0}};long long int res[2][2];void q_p(long long  N,long long mod){long long a = 1;long long tmp[2][2];for(int i = 0;i <2;++i)        for(int j = 0;j <2;++j)base[i][j] = 1;    base[1][1]= 0;res[0][0] = 1;res[0][1] = 0;res[1][0] = 0;res[1][1] = 1;while(a<=N){if(a&N){for(int i = 0;i<2;++i)for(int j = 0;j<2;++j){tmp[i][j] = 0;for(int  k = 0;k < 2;++k){tmp[i][j] += res[i][k] * base[k][j]; tmp[i][j] %= mod;}}for(int i = 0;i<2;++i)for(int j = 0;j<2;++j){res[i][j]=tmp[i][j];}}for(int i = 0;i<2;++i)            for(int j = 0;j<2;++j)            {                tmp[i][j] = 0;                for(int  k = 0;k < 2;++k){                    tmp[i][j] += base[i][k] * base[k][j];                    tmp[i][j] %= mod;                }            }        for(int i = 0;i<2;++i)            for(int j = 0;j<2;++j){                base[i][j]=tmp[i][j];            }a <<=1;}return;}int main(int argc, char const *argv[]){long long int n,mod;while(~scanf("%lld%lld",&n,&mod)){q_p(n,mod);printf("%lld\n",res[1][0]);}return 0;}



原创粉丝点击