1000. Fibonacci
来源:互联网 发布:微信发淘宝店铺链接 编辑:程序博客网 时间:2024/06/05 07:19
1000. 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).
Sample Input
9
Sample Output
34
本题比较简单,由于最多只需要计算到第100个斐波那契序列。所以直接用long long利用for循环方法得到答案。代码如下。
#include <iostream>using namespace std;int main(){ int n; while(cin>>n) { long long f0=0, f1=1; if(n==0) cout << 0 << endl; else if(n==1) cout << 1 << endl; else{ long long f2; for(int i=2;i<=n;i++) { f2=f0+f1; f0=f1; f1=f2; } f2=f2%(1000000007); cout << f2 << endl; } } return 0;}
1001. 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, ple Input
9
Sample Output
34
Hint
You may need to use “long long”.
#include <cmath>#include <cstring>using namespace std;#define MOD 1000000007struct matrix{ long long a[2][2];};matrix mul(matrix x,matrix y){ matrix m; memset(m.a,0,sizeof(m.a)); for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) m.a[i][j]=(m.a[i][j]+x.a[i][k]*y.a[k][j])%MOD; return m;}void power(int n){ matrix t,result; t.a[0][0]=1; t.a[0][1]=1; t.a[1][0]=1; t.a[1][1]=0; memset(result.a,0,sizeof(result.a)); for(int i=0;i<2;i++) result.a[i][i]=1; while(n) { if(n&1) result=mul(result,t); t=mul(t,t); n=n>>1; } cout << result.a[0][1] << endl;}int main(){ int n; while(cin>>n) { power(n); } return 0;}
- 1000. Fibonacci
- Fibonacci
- fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- Fibonacci
- 使用Openlayers v4时感觉需要记一下的东西
- C++ -- 数组定义字符串与指针定义字符串鲜为人知的秘密
- Java三大特性之封装
- 字符串连接strcat()实现及常见问题
- JMS学习
- 1000. Fibonacci
- java虚拟机 内存概念
- vs2017 新建项目 未指定的错误(异常来自HRESULT: 0x80004005(e_fail))redirection.config无法访问
- 第四届蓝桥杯C++B组——第39级台阶(dfs)
- w3c标准
- 面试经历
- 等差区间(写的很脑残)——中国(北方)大学生程序设计训练赛(第一周)F
- codeforces B. The Meeting Place Cannot Be Changed【二分】
- 队列(Queue)入门用法