1303.斐波那契前 n 项和

大家都知道 Fibonacci 数列吧,f1=1,f2=1,f3=2,f4=3,…,fn=fn−1+fn−2。

现在问题很简单,输入 n 和 m,求 fn 的前 n 项和 Snmodm。

输入格式
共一行,包含两个整数 n 和 m。

输出格式
输出前 n 项和 Snmodm 的值。

数据范围
1≤n≤2000000000,
1≤m≤1000000010
输入样例:
5 1000
输出样例:
12
image.png

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <iostream>
  4. #include <algorithm>
  5. using namespace std;
  6. typedef long long LL;
  7. const int N = 3;
  8. int n, m;
  9. void mul(int c[], int a[], int b[][N])
  10. {
  11. int temp[N] = {0};
  12. for (int i = 0; i < N; i ++ )
  13. for (int j = 0; j < N; j ++ )
  14. temp[i] = (temp[i] + (LL)a[j] * b[j][i]) % m;
  15. memcpy(c, temp, sizeof temp);
  16. }
  17. void mul(int c[][N], int a[][N], int b[][N])
  18. {
  19. int temp[N][N] = {0};
  20. for (int i = 0; i < N; i ++ )
  21. for (int j = 0; j < N; j ++ )
  22. for (int k = 0; k < N; k ++ )
  23. temp[i][j] = (temp[i][j] + (LL)a[i][k] * b[k][j]) % m;
  24. memcpy(c, temp, sizeof temp);
  25. }
  26. int main()
  27. {
  28. cin >> n >> m;
  29. int f1[N] = {1, 1, 1};
  30. int a[N][N] = {
  31. {0, 1, 0},
  32. {1, 1, 1},
  33. {0, 0, 1}
  34. };
  35. n -- ;
  36. while (n)
  37. {
  38. if (n & 1) mul(f1, f1, a); // res = res * a
  39. mul(a, a, a); // a = a * a
  40. n >>= 1;
  41. }
  42. cout << f1[2] << endl;
  43. return 0;
  44. }
  45. 作者:yxc
  46. 链接:https://www.acwing.com/activity/content/code/content/210521/
  47. 来源:AcWing
  48. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

求解斐波那契数列的若干方法

链接:https://www.acwing.com/blog/content/25/