UVA 10229 Modular Fibonacci

大意不再赘述。

思路:矩阵快速幂求fibonacci数列。开始我用INT WA了,其实中间结果超INT了,用long long 即可。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;

const int n = 2;
typedef long long LL;

int q, m;

int BASE;

void Mul(LL d[][2], LL a[][2], LL b[][2])
{
	LL c[2][2];
	memset(c, 0, sizeof(c));
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < n; j++)
		{
			for(int k = 0; k < n; k++)
			{
				c[i][j] += a[i][k] * b[k][j];
			}
			c[i][j] %= BASE;
		}
	}
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < n; j++)
		{
			d[i][j] = c[i][j];
		}
	}
}

LL power(int k)
{
	LL t[2][2] = {{0, 1}, {0, 1}};
	LL a[2][2] = {{0, 1}, {1, 1}};
	while(k)
	{
		if(k & 1) Mul(t, t, a);
		Mul(a, a, a);
		k /= 2;
	}
	return t[0][0];
}

void solve()
{
	BASE = 1<<m;
	LL ans = power(q);
	printf("%lld\n", ans);
}

int main()
{
	while(~scanf("%d%d", &q, &m))
	{
		solve();
	}
	return 0;
}


你可能感兴趣的:(UVA 10229 Modular Fibonacci)