<OJ_Sicily>Fibonacci
来源:互联网 发布:淘宝云客服考试 编辑:程序博客网 时间:2024/06/01 15:31
Fibonacci_1
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, …
Given an integer n, your goal is to compute the last Fn mod (10^9 + 7).
Input
The input test file will contain a single line containing n (n ≤ 100).
There are multiple test cases!
Output
For each test case, print the Fn mod (10^9 + 7).
解题思路:一般斐波那契数列的求解有多种,下面通过递归和幂次数实现
#include <math.h>using namespace std;int Fibonacci_1(int n){ if(n==0 || n== 1)return n; int fn = Fibonacci_1(n-1) +Fibonacci_1(n-2); return fn %((int)pow(10,9)+7); //每次都进行取模,防止数值过大溢出}int main(int argc, const char * argv[]) { int n; while(cin >> n) { cout << Fibonacci_1(n) << endl; } return 0;}
Fibonacci_2
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, …
Given an integer n, your goal is to compute the last Fn mod (10^9 + 7).
Input
The input test file will contain a single line containing n (n ≤ 2^31-1).
There are multiple test cases!
Output
For each test case, print the Fn mod (10^9 + 7).
解题思路:相对于Fibonacci_1,不同的是,输入的n的范围值大了很多(n ≤ 2^31-1).考虑到时间限制,需要使用幂次方矩阵来解决这个问题。
斐波那契数列用矩阵表示如下:
#include <iostream>using namespace std;#define M 1000000007 struct Matrix{ long long v[2][2];};Matrix matrixMul(Matrix a, Matrix b) { //两个矩阵相乘 Matrix temp; for (int i = 0; i != 2; i++) { for (int j = 0; j != 2; j++) { temp.v[i][j] = 0; for (int k = 0; k != 2; k++) { temp.v[i][j] += a.v[i][k] * b.v[k][j]; temp.v[i][j] %= M; } } } return temp;}Matrix power(Matrix a, Matrix b, long long n) { while (n) { if (n & 1) { b = matrixMul(b, a); } n >>= 1; a = matrixMul(a, a); } return b;}int main(int argc, char* argv[]) { Matrix a = {1, 1, 1, 0}, b = {1, 0, 0, 1}; long long n; while (cin >> n) { if (n == 0) cout << 0 << endl; else { Matrix result = power(a, b, n - 1); cout << result.v[0][0] << endl; } } return 0;}
后记:
1.刚开始的时候,并没有注意到数列递增的趋势,使用int是无法表示全部所需数列值的。因此后面统一变成了long long型
2.幂次方解决方法能够大大提高速度。代码新手,有什么建议和意见欢迎提出
- <OJ_Sicily>Fibonacci
- <OJ_Sicily>Hanoi_Tower_Sequence
- <OJ_Sicily>Maze
- <OJ_Sicily>Bicoloring
- <OJ_Sicily>DAG
- <OJ_Sicily>Forest
- <OJ_Sicily>Maze
- <OJ_Sicily>Rails
- <OJ_Sicily>Pair
- <OJ_Sicily>Polynomial
- <OJ_Sicily>Connection
- <OJ_Sicily>Single-link Clustering
- <OJ_Sicily>Order Crossover
- <OJ_Sicily>N_Queen Problem
- <OJ_Sicily>1134积木分发
- <OJ_Sicily>1438Shopaholic
- <OJ_Sicily>Travelling Salesman Problem
- <OJ_Sicily>1240Faulty_Odometer
- Android开发之adapter
- 安卓随记
- 窗体进行缩放时,隐藏滚动条
- 几种排序算法的c#实现
- 对“视觉机器学习20讲配套仿真代码”的研究心得---SVM方法
- <OJ_Sicily>Fibonacci
- 【Caffe实践】基于Caffe的人脸检测实现
- Canvas画布调整
- Win7 U盘安装Ubuntu16.04 双系统详细教程
- Android 可拖拽的GridView效果实现, 长按可拖拽和item实时交换
- OpenCV:imshow()/imwrite()数据类型问题
- 设计模式笔记:工厂模式,建造者模式
- java bean、mapper、service、dao代码生成器
- sublime text3 git插件乱码问题