結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
ユーザー okok
提出日時 2019-06-24 13:48:39
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,775 bytes
コンパイル時間 1,313 ms
コンパイル使用メモリ 86,932 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-02 00:40:38
合計ジャッジ時間 2,107 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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,376 KB
testcase_04 AC 2 ms
4,376 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 2 ms
4,380 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 2 ms
4,380 KB
testcase_11 AC 2 ms
4,380 KB
testcase_12 AC 2 ms
4,380 KB
testcase_13 AC 1 ms
4,376 KB
testcase_14 AC 2 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<string>
#include<iomanip>
#include<cmath>
#include<vector>
#include<algorithm>

using namespace std;

#define int long long
#define rep(i,n) for(int i = 0; i < (n); i++)
#define endl "\n"

const long long INF = (long long)1e18;
// const long long MOD = (long long)1e9 + 7; 
// long long MOD;

string yn(bool f){return f?"Yes":"No";}
string YN(bool f){return f?"YES":"NO";}

#define MAX

int solve(int n, int MOD){
	if(n <= 1) return n;
	vector<vector<int>> ans(2,vector<int>(1)), temp(2,vector<int>(1)), matrix1(2,vector<int>(2)), matrix2(2,vector<int>(2)), matrix3(2,vector<int>(2));
	ans[0][0] = 1;
	ans[1][0] = 0;
	
	matrix1[0][0] = 1;
	matrix1[0][1] = 1;
	matrix1[1][0] = 1;
	matrix1[1][1] = 0;
	n--;
	
	while(n){
		if(n&1){
			temp.clear();
			temp.resize(2,vector<int>(1,0));
			
			for(int i = 0; i < matrix1.size(); i++){
				for(int j = 0; j < ans[0].size(); j++){
					for(int k = 0; k < ans.size(); k++){
						temp[i][j] += matrix1[i][k]*ans[k][j];
						temp[i][j] %= MOD;
					}
				}
			}
			ans = temp;
		}
		
		matrix3.clear();
		matrix3.resize(2,vector<int>(2,0));
		
		matrix2 = matrix1;
		
		for(int i = 0; i < matrix1.size(); i++){
			for(int j = 0; j < matrix1.size(); j++){
				for(int k = 0; k < matrix1.size(); k++){
					matrix3[i][j] += matrix1[i][k]*matrix2[k][j];
					matrix3[i][j] %= MOD;
				}
			}
		}
		
		matrix1 = matrix3;
		
		n >>= 1;
		
		// cout<<"matrix "<<matrix1[0][0]<<" "<<matrix1[0][1]<<endl;
		// cout<<"matrix "<<matrix1[1][0]<<" "<<matrix1[1][1]<<endl;
		
		// cout<<"ans "<<ans[0][0] <<" "<<ans[0][1]<<endl;
	}
	
	return ans[0][0];
}

signed main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);
	
	int n, m;
	
	cin>>n>>m;
	
	
	cout<<solve(n-1,m)<<endl;
	
	return 0;
}
0