結果
問題 |
No.526 フィボナッチ数列の第N項をMで割った余りを求める
|
ユーザー |
|
提出日時 | 2024-03-07 14:29:00 |
言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 2 ms / 2,000 ms |
コード長 | 1,259 bytes |
コンパイル時間 | 3,259 ms |
コンパイル使用メモリ | 251,788 KB |
実行使用メモリ | 6,820 KB |
最終ジャッジ日時 | 2024-09-29 18:39:35 |
合計ジャッジ時間 | 3,895 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 12 |
ソースコード
#include <bits/stdc++.h> using namespace std; #define ll long long ll mod; // 行列積 vector<vector<ll>> mat_mul(vector<vector<ll>> &a, vector<vector<ll>> &b) { vector<vector<ll>> ret((int)a.size(), vector<ll>((int)b[0].size())); for (int i = 0; i < (int)a.size(); i++) { for (int j = 0; j < (int)b[0].size(); j++) { for (int k = 0; k < (int)b.size(); k++) { ret[i][j] += a[i][k] * b[k][j]; ret[i][j] %= mod; } } } return ret; } // 行列累乗 vector<vector<ll>> mat_pow(vector<vector<ll>> a, long long n) { vector<vector<ll>> ret((int)a.size(), vector<ll>((int)a.size())); // 単位行列で初期化 for (int i = 0; i < (int)a.size(); i++) { ret[i][i] = 1; } // 繰り返し二乗法 while (n > 0) { if (n & 1) { ret = mat_mul(a, ret); } a = mat_mul(a, a); n >>= 1; } return ret; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; mod = m; vector<vector<ll>> X(2, vector<ll>(2)); X[0][0] = 1; X[0][1] = 1; X[1][0] = 1; X[1][1] = 0; vector<vector<ll>> Y(2, vector<ll>(1)); Y[0][0] = 1; Y[1][0] = 0; auto X_POW = mat_pow(X, n - 2); auto ans = mat_mul(X_POW, Y); cout << ans[0][0] << '\n'; return 0; }