작심 24/7

[백준] 4150번 피보나치 수 본문

백준

[백준] 4150번 피보나치 수

모닝수박 2020. 5. 26. 16:17
 

4150번: 피보나치 수

문제 피보나치 수열은 다음과 같이 그 전 두 항의 합으로 계산되는 수열이다. 첫 두 항은 1로 정의된다. f(1) = 1, f(2) = 1, f(n > 2) = f(n − 1) + f(n − 2) 정수를 입력받아, 그에 해당하는 피보나치 수를

www.acmicpc.net

정답이 1000자리 이하라는 말을 보고 눈을 의심했었다.

int나 long long으로는 절대 풀 수 없기 때문에 string을 이용하여 답을 구했다.

 

계산할 때는 숫자를 뒤에서부터 한 자리씩 int로 바꾸어 계산 하였고

계산 완료된 값은 string형으로 배열에 넣어주었다.

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

int main() {
	int n;
	cin >> n;

	fibonacci.push_back("0");
	fibonacci.push_back("1");
	
	for (int i = 2; i <= n; i++) {
		int a = fibonacci[i - 1].size(), b = fibonacci[i - 2].size(), res = 0, add = 0;
		string result, temp;
		for (int j = a - 1; j >= 0; j--) {
			if (j - (a - b) >= 0) res = (fibonacci[i - 1][j] - 48) + (fibonacci[i - 2][j - (a - b)] - 48) + add;
			else res = fibonacci[i - 1][j] - 48 + add;
			if (res >= 10) {
				res -= 10;
				add = 1;
			}
			else add = 0;
			temp = result;
			result = to_string(res) + temp;
			if (j == 0 && add == 1) {
				temp = result;
				result = to_string(add) + temp;
			}
		}
		fibonacci.push_back(result);
	}

	cout << fibonacci[n];

	return 0;
}

 

'백준' 카테고리의 다른 글

[백준] 1149번 RGB거리  (0) 2020.05.27
[백준] 1003번 피보나치 함수  (0) 2020.05.26
[백준] 14889번 스타트와 링크  (0) 2020.05.25
[백준] 14888번 연산자 끼워넣기 (C++, JAVA)  (0) 2020.05.25
[백준] 2580번 스도쿠  (0) 2020.05.25
Comments