# PAT_甲级_2020年冬季考试 7-1 The Closest Fibonacci Number

## 7-1 The Closest Fibonacci Number (20 分)

The Fibonacci sequence Fn is defined by \$\$F_{n+2} =F_{n+1} +F​_n \;\;for \;\;n≥0, with \;\;F_​0 =0 \;\;and\;\; F_​1 =1.\$\$ The closest Fibonacci number is defined as the Fibonacci number with the smallest absolute difference with the given integer N.

Your job is to find the closest Fibonacci number for any given N.

### Input Specification:

Each input file contains one test case, which gives a positive integer N (≤10^8).

### Output Specification:

For each case, print the closest Fibonacci number. If the solution is not unique, output the smallest one.

`305`

`233`

### Hint:

Since part of the sequence is { 0, 1, 1, 2, 3, 5, 8, 12, 21, 34, 55, 89, 144, 233, 377, 610, ... }, there are two solutions: 233 and 377, both have the smallest distance 72 to 305. The smaller one must be printed out.

### 注意点

• 1、直接暴力递归会导致测试点5运行超时

### AC代码

``````#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;

int dp[1000000];

int F(int n) {
if (n == 0 || n == 1) {
dp[n] = n;
return n;
}
if(dp[n]!=-1){
return dp[n];
}else{
dp[n] = F(n - 1) + F(n - 2);
}
return dp[n];
}

int main() {
int N;
scanf("%d", &N);
memset(dp, -1, sizeof(dp));
dp[0] = dp[1] = 1;
int k;
for (int i = 0;; ++i) {
if (dp[i] == -1) {
dp[i] = F(i);
}
if (dp[i] >= N) {
k = i;
break;
}
}
int a = abs(dp[k] - N);
int b = abs(dp[k - 1] - N);
if (a < b) {
printf("%d", dp[k]);
} else {
printf("%d", dp[k - 1]);
}
return 0;
}``````

543 声望
11 粉丝