結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
コンテスト
ユーザー 小畑裕貴
提出日時 2026-02-20 15:09:13
言語 C++17
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,309 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,710 ms
コンパイル使用メモリ 137,768 KB
実行使用メモリ 7,844 KB
最終ジャッジ日時 2026-02-20 15:09:21
合計ジャッジ時間 3,384 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 12
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <algorithm>
#include <array>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;

typedef vector<vector<long long>> mat;
long long MOD = 1000000007;


mat mat_mul(const mat &A, const mat &B, long long m) {
    mat res(A.size(), vector<long long>(B[0].size(), 0));
    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)A[0].size(); k++) {
                res[i][j] = (res[i][j] + A[i][k] * B[k][j]) % m;
            }
        }
    }
    return res;
}


mat mat_pow(mat A, long long n, long long m) {
    mat res(A.size(), vector<long long>(A[0].size(), 0));
    for (int i = 0; i <(int)A.size(); i++) res[i][i] = 1;
    while (n > 0) {
        if (n % 2 == 1) res = mat_mul(A, res, m);
        A = mat_mul(A, A, m);
        n /= 2;
    }
    return res;
}


int main() {
    long long n, m;
    cin >> n >> m;
    mat A(2, vector<long long>(2));
    A[0][0] = 0;
    A[0][1] = 1;
    A[1][0] = 1;
    A[1][1] = 1;
    mat b(2, vector<long long>(1));
    b[0][0] = 0;
    b[1][0] = 1;
    b = mat_mul(mat_pow(A, n-2, m), b, m);
    cout << b[1][0] << endl;
}
0