10229 - Modular Fibonacci

本文介绍了一种使用矩阵乘法加速Fib数列计算的方法,并通过分治策略进一步优化,实现了快速计算F[n]并对2^m取模的功能。



使用矩阵实现Fib的运算

/*
推荐:四星

题意:Fib数列,输入n、m,输出F[n] % 2^m

思路:正常的解法会导致超时,网上看到一种解法,使用矩阵乘法加速,然后分治求解。
*/
#include <cstdio>
const int nMax = 30;
long long a[4],b[4];
int M;
void bsearch(int n)
{
	if(1 == n)
	{
		a[0] = a[1] = a[2] = 1;
		a[3] = 0;
		return ;
	}
	bsearch(n>>1);
	b[0] = a[0] * a[0] + a[1] * a[2];
	b[1] = a[0] * a[1] + a[1] * a[3];
	b[2] = a[2] * a[0] + a[3] * a[2];
	b[3] = a[2] * a[1] + a[3] * a[3];
	a[0] = b[0] % M;
	a[1] = b[1] % M;
	a[2] = b[2] % M;
	a[3] = b[3] % M;
	if(n & 1)//当n为奇数时
	{
		b[0] = a[0] + a[1];
		b[1] = a[0];
		b[2] = a[2] + a[3];
		b[3] = a[2];
		a[0] = b[0] % M;
		a[1] = b[1] % M;
		a[2] = b[2] % M;
		a[3] = b[3] % M;
	}
}
int main()
{
	//freopen("f://data.in", "r", stdin);
	int n, m;
	while(scanf("%d%d", &n, &m) != EOF)
	{
		if(0 == n) printf("0\n");
		else if(1 == n) printf("1\n");
		else
		{
			M = 1 << m;
			bsearch(n-1);
			printf("%d\n", a[0]);
		}
	}
	return 0;
}


The well-known Fibonacci sequence is: 𝐹𝑖 = 𝐹𝑖−1 + 𝐹𝑖−2 for 𝑖 ≥ 2, 𝐹0 = 0, 𝐹1 = 1. Tom discovers that the Fibonacci number grows very quickly, for example 𝐹40 = 102334155. To make further discovery of the Fibonacci numbers, Tom takes the following steps: Take the first 𝒏 Fibonacci numbers (exclude F0) S1 ={F1, F2, ..., Fn} Modulo each Fibonacci number by a positive integer Q, i.e. A𝑖 = 𝐹𝑖 % Q and obtain a new sequence S2 ={A1, A2, ..., An } Sort the numbers in S2 from small to large and obtain sequence S3 S2 ={A1,A2, ...,An } → S3 ={c1, c2, ..., cn } For numbers in sequence S3, calculate the weighted sum modular Q (k ⋅ 𝑐𝑘) %𝑄 = (1 ⋅ 𝑐1 + 2 ⋅ 𝑐2 + 3 ⋅ 𝑐3 + ⋯ + 𝑛 ⋅ 𝑐𝑛)%𝑸 Can you write a program to calculate the result? Input The input contains multiple test cases. The first line of the input is a number T (1 ≤ T ≤ 100), indicating the number of test cases. Each test case contains two integers n (2 ≤ n ≤ 5,000,000) and Q (2 ≤ Q ≤ 1000,000,000) in one line. Output For each test case, print the weighted sum in a separate line. Sample Sample input 4 5 100 5 3 15 13 5000000 1000000000 Sample output 46 2 11 973061125 Explanation: In the second sample: the first 5 Fibonacci numbers are {1, 1, 2, 3, 5}, after modular 3 it becomes {1, 1, 2, 0, 2} and after sorting it is {0,1,1,2,2}, hence the weighted sum is 0 ⋅ 1 + 1 ⋅ 2 + 1 ⋅ 3 + 2 ⋅ 4 + 2 ⋅ 5 = 23 After modular 3 it is 23 % 3 = 2. Constraint and hint radix sort
12-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值