bit 1047 Fibonacci Numbers

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值