# 2749 피보나치 수 3

```cpp
#include"2749.h"
using namespace std;
const int MOD = 1000000;
typedef long long ll;

map<ll, int> dict;

int Fibo_L(int n)
{
	if (n == 0) return 0;
	if (n == 1) return 1;
	else return Fibo_L(n - 1) + Fibo_L(n - 2);
}

ll Fibo(ll n)
{
	if (n <= 3) return Fibo_L(n);
	if (dict.count(n)) return dict[n];
	ll res;
	if (n % 2 == 0) // 짝수일 경우
	{
		ll a = Fibo(n / 2) % MOD;
		ll b = Fibo(n / 2 + 1) % MOD;
		ll c = Fibo(n / 2 - 1) % MOD;
		res = a * (b + c) % MOD;
	}
	else // 홀수일 경우
	{
		ll a = Fibo((n + 3) / 2) % MOD;
		ll b = Fibo((n - 1) / 2) % MOD;
		ll c = Fibo((n + 1) / 2) % MOD;
		ll d = Fibo((n - 3) / 2) % MOD;
		res = (a*b + c*d) % MOD;
	}
	dict[n] = res;
	return res;
}


void B2749::Solution()
{
	long long n;
	cin >> n;
	cout << Fibo(n);
}
```

실수

* `n<=3` 조건을 `<3`으로 걸어서 3이면 무한히 안 끝났었음
* 점화식 전개할 때 각각 F\_2, F\_1으로 놔야 하는데 둘 다 F\_1으로 놔버려서 식 잘못 정리됐었음
* 캐싱 도입 안 했더니 계산량이 지수적으로 증가해서 시간 초과.

```cpp
#include <iostream>
using namespace std;
long long arr[2000001];
int main() {
    arr[0] = 0;
    arr[1] = 1;
    long long N;
    cin>>N;
    N%=1500000;
    for(int i=2;i<=N;i++)
        arr[i]=(arr[i-1]+arr[i-2])%1000000;
    cout<<arr[N];
}
```

피사노 주기를 이용하면 어처구니 없게 짧게 풀 수 있다. 속도는 약간 더 느리긴 함.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lazyartisan.gitbook.io/note/main-page/algorithm/undefined-1/2749-3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
