개발자일걸요..?

11444번 피보나치 수 6 본문

알고리즘코딩/Baekjoon Online Judge

11444번 피보나치 수 6

Re_A 2021. 4. 3. 22:22
728x90
반응형

 

문제링크 : www.acmicpc.net/problem/11444

 

11444번: 피보나치 수 6

첫째 줄에 n이 주어진다. n은 1,000,000,000,000,000,000보다 작거나 같은 자연수이다.

www.acmicpc.net


문제

피보나치 수는 0과 1로 시작한다. 0번째 피보나치 수는 0이고, 1번째 피보나치 수는 1이다. 그 다음 2번째 부터는 바로 앞 두 피보나치 수의 합이 된다.

이를 식으로 써보면 Fn = Fn-1 + Fn-2 (n ≥ 2)가 된다.

n=17일때 까지 피보나치 수를 써보면 다음과 같다.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597

n이 주어졌을 때, n번째 피보나치 수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 n이 주어진다. n은 1,000,000,000,000,000,000보다 작거나 같은 자연수이다.

출력

첫째 줄에 n번째 피보나치 수를 1,000,000,007으로 나눈 나머지를 출력한다.

예제 입력 1

1000

예제 출력 1

517691607

<참고>

2021.04.01 - [Baekjoon Online Judge] - 2740번 행렬 곱셈

2021.04.02 - [Baekjoon Online Judge] - 10830번 행렬 제곱

 

 

메모리 : 2020KB   시간 : 0ms

#include <iostream>
#include <vector>
using namespace std;

typedef unsigned long long ll;
typedef vector<vector<ll>> matrix;

matrix operator*(matrix &f, matrix &s) {
	matrix calculate(2, vector < ll>(2));
	for (int i = 0; i < 2; i++) {
		for (int j = 0; j < 2; j++) {
			ll answer = 0;
			for (int a = 0; a < 2; a++) {
				answer += (f[i][a] * s[a][j]) % 1000000007;
			}
			calculate[i][j] = answer % 1000000007;
		}
	}
	return calculate;
}
matrix power(matrix now, ll N){
	matrix unit(2, vector<ll>(2));
	unit = { {1,1},{1,0} };

	while (N > 0) {
		if (N % 2 == 1) {
			now = unit * now;
		}
		N /= 2;
		unit = unit * unit;
	}
	return now;
}

int main() {
	ll N = 0;
	cin >> N;

	if (N <= 1) cout << N << "\n";
	else {
		matrix now(2, vector<ll>(2));
		now = { {1,0},{0,1} };

		matrix result = power(now, N);
		cout << result[0][1] << "\n";
	}
	return 0;
}

 

+) 시간초과

#include <iostream>
#include <vector>
using namespace std;

typedef unsigned long long ll;

int main() {
	ll N = 0;
	cin >> N;

	vector<vector<ll>> unit(2, vector<ll>(2));
	for (int i = 0; i < 2; i++) {
		for (int j = 0; j < 2; j++) {
			unit[i][j] = 1;
		}
	}
	unit[0][0] = 0;

	vector<ll>base;
	base.push_back(0);
	base.push_back(1);
	N--; 

	
	while (N--) {
		vector<ll> cal(2, 0);
		for (int i = 0; i < 2; i++) {
			for (int a = 0; a < 2; a++) {
				cal[i] += (unit[a][i] * base[a]) % 1000000007;
				cal[i] %= 1000000007;
			}
		}
		base = cal;
	}
	cout << base[1]<< "\n";

	return 0;
}
반응형

'알고리즘코딩 > Baekjoon Online Judge' 카테고리의 다른 글

10812번 바구니 순서 바꾸기  (0) 2021.11.04
18870번 좌표 압축  (0) 2021.04.06
10830번 행렬 제곱  (0) 2021.04.02
2740번 행렬 곱셈  (0) 2021.04.01
12015번 가장 긴 증가하는 부분 수열  (0) 2021.03.30
Comments