結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
ユーザー aiutarsiaiutarsi
提出日時 2021-09-16 23:20:38
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,242 bytes
コンパイル時間 1,735 ms
コンパイル使用メモリ 175,072 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-12 04:15:42
合計ジャッジ時間 2,612 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
#define _GLIBCXX_DEBUG
using namespace std;
typedef long long ll;

ll MOD;

//行列A*行列Bの計算(ただし, A*Bが定義できること, Aの列=Bの行)
template <typename T>
vector<vector<T>>  mul(vector<vector<T>> &A, vector<vector<T>> &B) {
  vector<vector<T>> C(A.size(), vector<T> (B.at(0).size()));
  for (int i = 0; i < A.size(); i++) {
    for (int j = 0; j < B.size(); j++) {
      for (int k = 0; k < B.at(0).size(); k++) {
        C.at(i).at(k) = (C.at(i).at(k) + A.at(i).at(j)*B.at(j).at(k))%MOD;
      }
    }
  }
  return C;
}

//A^nの計算(Aは正方行列)
template <typename T>
vector<vector<T>> power(vector<vector<T>> A, T n) {
  vector<vector<T>> C(A.size(), vector<T> (A.size()));
  for (int i = 0; i < A.size(); i++) C.at(i).at(i) = 1; //単位行列
  //繰り返し自乗法(行列でも同じ, 同じAを複数回かけるだけだから, Aを入れ替えても行列の積は変化がないからok)
  while (n) {
    if (n & 1) C = mul(C, A);
    A = mul(A, A);
    n >>= 1; //nを1bit右シフト(n/2)
  }
  return C;
}

int main() {
  ll n; cin >> n >> MOD;
  vector<vector<ll>> A(2, vector<ll> (2));
  A = {{1,1}, {1,0}};
  A = power(A, n-1);
  cout << A.at(1).at(0) << endl;
}
0