[ ALGORITHM ]/[ 백 준 ]

[BAEKJOON] 1003번 피보나치 함수

HiStar__ 2020. 6. 22. 15:39

문 제

 

 

소 스  코 드

#include <iostream>

constexpr int ZERO_INDEX	{ 0 };
constexpr int ONE_INDEX		{ 1 };


void Fibonacci(const int&);

int main() {
	int T;
	std::cin >> T;

	int *temp		{ new int[T] };

	for (int i = 0; i < T; ++i)		std::cin >> temp[i];
	for (int i = 0; i < T; ++i)		Fibonacci(temp[i]);

	delete[] temp;
}


void Fibonacci(const int& n) {

	int first[2]		{ 0, 1 };		// 1
	int second[2]		{ 1, 0 };		// 0

	int temp[2]		{ 0, 0 };

	if (0 == n) {
		std::cout << second[ZERO_INDEX] << " " << second[ONE_INDEX] << '\n';
		return;
	}
	else if (1 == n) {
		std::cout << first[ZERO_INDEX] << " " << first[ONE_INDEX] << '\n';
		return;
	}
	else {
		for (int i = 0; i < n - 1; ++i) {
			temp[ZERO_INDEX] = first[ZERO_INDEX];
			temp[ONE_INDEX] = first[ONE_INDEX];


			first[ZERO_INDEX] = first[ZERO_INDEX] + second[ZERO_INDEX];
			first[ONE_INDEX] = first[ONE_INDEX] + second[ONE_INDEX];

			second[ZERO_INDEX] = temp[ZERO_INDEX];
			second[ONE_INDEX] = temp[ONE_INDEX];
		}
	}

	std::cout << first[ZERO_INDEX] << " " << first[ONE_INDEX] << '\n';

}

 

풀 이

 

  • 1 { 0, 1 } 0 { 1, 0 }
  • N - 1, N - 2 일 때 앞에 N - 1이 다음의 N - 2가 반복되는 것을 알 수 있다.
    3 - 2, 1 | 4 - 3, 2 | 5 - 4, 3

 

결 과 값

 

 

문 제  출 처

문제 링크 : [ BAEKJOON ] : https://www.acmicpc.net/problem/1003