結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
ユーザー Yuki Iwahashi
提出日時 2025-09-18 10:31:45
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,066 bytes
コンパイル時間 1,883 ms
コンパイル使用メモリ 203,460 KB
実行使用メモリ 7,716 KB
最終ジャッジ日時 2025-09-18 10:31:48
合計ジャッジ時間 3,199 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 6 WA * 6
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;
using ll = long long;



int M;

vector<vector<int>> mul(vector<vector<int>> A, vector<vector<int>> B) {
  int N = A.size(); int K = A[0].size(); int L = B[0].size();
  vector<vector<int>> res(N, vector<int>(L,0));
  if (K != B.size()) return res;
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < L; ++j) {
      for (int k = 0; k < K; ++k) {
        res[i][j] += (A[i][k] * B[k][j]) % M;
      }
    }
  }
  return res; 
}

vector<vector<int>> power_matrix(vector<vector<int>> A, int n) {
  if (n == 1) return A;
  if (n % 2) {
    return mul(A, power_matrix(A, n-1));
  }
  else {
    auto B = power_matrix(A, n / 2);
    return mul(B,B) ;
  }
}

int main() {
  int N; cin >> N >> M;
  if (N == 1) {
    cout << 0 << endl;
    return 0;
  }
  else if (N == 2) {
    cout << 1 << endl;
    return 0;
  }
  vector<vector<int>> fib = {{1,1},{1,0}};
  vector<vector<int>> power = power_matrix(fib, N - 2);

  vector<vector<int>> res = {{1},{0}};
  res = mul(power, res);
  cout << res[0][0] << endl;
  return 0;
}
0