結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
ユーザー Kou MishimaKou Mishima
提出日時 2023-04-14 08:31:44
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 953 bytes
コンパイル時間 1,976 ms
コンパイル使用メモリ 169,840 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-18 08:42:43
合計ジャッジ時間 2,692 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 2 ms
5,376 KB
testcase_07 AC 2 ms
5,376 KB
testcase_08 AC 2 ms
5,376 KB
testcase_09 AC 2 ms
5,376 KB
testcase_10 AC 2 ms
5,376 KB
testcase_11 AC 2 ms
5,376 KB
testcase_12 AC 2 ms
5,376 KB
testcase_13 AC 2 ms
5,376 KB
testcase_14 AC 2 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
#define mat vector<vector<long>>
long MOD;
/// 行列積
mat mat_mul(mat &a, mat &b) {
  mat res(a.size(), vector<long>(b[0].size()));
  for (int i = 0; i < a.size(); i++) {
    for (int j = 0; j < b[0].size(); j++) {
      for (int k = 0; k < b.size(); k++) {
        (res[i][j] += a[i][k] * b[k][j]) %= MOD;
      }
    }
  }
  return res;
}

/// 行列累乗
mat mat_pow(mat a, long long n) {
  mat res(a.size(), vector<long>(a.size()));
  // 単位行列で初期化
  for (int i = 0; i < a.size(); i++)
    res[i][i] = 1;
  // 繰り返し二乗法
  while (n > 0) {
    if (n & 1) res = mat_mul(a, res);
    a = mat_mul(a, a);
    n >>= 1;
  }
  return res;
}

signed main()
{
  long n;
  cin >> n>>MOD;
  n--;
  // フィボナッチ数列の行列累乗
  mat m(2, vector<long>(2));
  m[0][0] = m[0][1] = m[1][0] = 1;
  m[1][1] = 0;
  m = mat_pow(m, n);
  long ans = m[1][0];
  cout << ans << endl;
}
0