【算法学习】POJ3070——利用分治法来计算Fibonacci数列的值
来源:互联网 发布:细菌觅食算法 编辑:程序博客网 时间:2024/05/22 12:56
Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
099999999991000000000-1
Sample Output
0346266875
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
我的解决办法是利用了类似于求x^n的分治法来加快矩阵运算,使得计算Fibonacci数列第n项的时间复杂度变成了O(lgn),比普通算法的O(n)更快
这题有一个比较坑的点就是每一步矩阵运算都要进行一次mod1000
代码如下:
#include <iostream>using namespace std;struct matrix { long x00; long x01; long x10; long x11;};matrix matrix_mul ( matrix a, matrix b ) { matrix c = {0,0,0,0}; c.x00 = (a.x00*b.x00 + a.x01*b.x10)%10000; c.x01 = (a.x00*b.x01 + a.x01*b.x11)%10000; c.x10 = (a.x10*b.x00 + a.x11*b.x10)%10000; c.x11 = (a.x10*b.x01 + a.x11*b.x11)%10000; return c;}matrix matrix_pow ( matrix a, long n ) { if ( n == 1 ) { return a; } else if ( n%2 == 0 ) { matrix temp = matrix_pow(a,n/2); return matrix_mul(temp,temp); } else { matrix temp = matrix_pow(a,(n-1)/2); matrix temp1 = matrix_mul(temp,temp); return matrix_mul(temp1,a); }}long fibonacci_value ( long n ) { if( n == 0 ) { return 0; } else { matrix root = {1,1,1,0}; root = matrix_pow(root,n); return root.x01 % 10000; }}int main(){ long input[100] = {0}; int num = 0; long temp; while (true) { cin >> temp; if( temp != -1 ) { input[num++] = temp; } else { break; } } for( int i = 0; i < num; ++i ) { cout << fibonacci_value(input[i]) << endl; } return 0;}
- 【算法学习】POJ3070——利用分治法来计算Fibonacci数列的值
- 算法学习笔记(3)——分治法,Fibonacci数列,Strassen算法
- 计算fibonacci数列logn的算法
- Fibonacci数列的计算
- 算法思想学习系列:分治法——求数列的逆序数
- 【算法学习】利用分治法计算x的n次幂
- 【poj3070】Fibonacci——矩阵快速幂
- 矩阵快速幂 求Fibonacci数列poj3070
- fibonacci数列的矩阵算法
- Swift学习—— 求Fibonacci数列
- poj3070 Fibonacci 斐波那契数列的第n项的矩阵求法
- 网易—Fibonacci数列
- 基于Cache的Fibonacci数列的计算
- [POJ3070]Fibonacci sequence——矩阵+快速幂
- POJ3070 Fibonacci
- Fibonacci(poj3070)
- POJ3070 Fibonacci
- poj3070 Fibonacci
- [算法学习笔记]线性时间排序----计数排序
- HDU 2594 Simpsons’ Hidden Talents (kmp)
- 随笔2
- 线程 —— 使用匿名内部类的方式启动线程
- Android自定义Animation实现3D翻转按钮
- 【算法学习】POJ3070——利用分治法来计算Fibonacci数列的值
- HDU1166 敌兵布阵[线段树/树状数组]
- 通过迭代器来获得对应元素的下标╮(╯▽╰)╭ ~
- centos6.x常用命令
- POJ-2585 Window Pains
- 服务器用map来接收数据
- poj1083贪心
- redis hashes类型操作
- Android Studio使用SVN代码管理工具遇到的问题及解决办法