結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
ユーザー TomorrowNextTomorrowNext
提出日時 2021-03-22 02:14:10
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,173 bytes
コンパイル時間 1,598 ms
コンパイル使用メモリ 170,936 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-14 20:26:13
合計ジャッジ時間 2,312 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include "bits/stdc++.h"

using namespace std;
using ll = long long;

ll N, M;

vector<vector<ll>> mult(const vector<vector<ll>>& m1, const vector<vector<ll>>& m2) {
    vector<vector<ll>> ret(2, vector<ll>(2, 0));
    for (ll i = 0; i < 2; ++i) {
        for (ll j = 0; j < 2; ++j) {
            for (ll k = 0; k < 2; ++k) {
                ret[i][j] += (m1[i][k] * m2[k][j]) % M;
                ret[i][j] %= M;
            }
        }
    }
    return ret;
}

vector<vector<ll>> pow(const vector<vector<ll>>& m, ll n) {
    if (n == 1) {
        return m;
    }
    vector<vector<ll>> ret = pow(m, n / 2);
    ret = mult(ret, ret);
    if (n % 2 == 1) {
        ret = mult(ret, m);
    }
    return ret;
}

void Main() {
    cin >> N >> M;
    if (N == 1) {
        cout << 0 << endl;
        return;
    }
    else if (N == 2) {
        cout << 1 << endl;
        return;
    }
    vector<vector<ll>> C(2, vector<ll>(2, 0));
    C[0][0] = 1;
    C[0][1] = 1;
    C[1][0] = 1;
    vector<vector<ll>> Cpow = pow(C, N - 2);
    ll ans = Cpow[0][0];
    cout << ans << endl;
}

int main() {
    std::cout << std::fixed << std::setprecision(15);
    Main();
    return 0;
}
0