PAT 2020年冬季 7-1 The Closest Fibonacci Number (20 分)
The Fibonacci sequence Fn is defined by Fn+2=Fn+1+Fn for n≥0, with F0=0 and F1=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.
Sample Input:
305
Sample Output:
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.
实现思路:
是一道斐波那契数列的基本题,一开始直接上手直接就递归法了,很简单,但是明显的有一个数据点运行超时了,所以立马就应该换其他思路了,采用非递归法,能够实现递归法实现的办法就是迭代,所以本题只需要迭代保存值就可以了。
AC代码:
#include <iostream>
#include <cmath>
using namespace std;
int sq[1010];
int main() {
sq[0]=0;
sq[1]=1;
int idx,n;
cin>>n;
for(int i=2; i<1010; i++) {
sq[i]=sq[i-1]+sq[i-2];
if(sq[i]>1e8) {
idx=i;
break;
}
}
int minVal=0x7fffffff,minIdx;
for(int i=0; i<idx; i++) {
if(abs(sq[i]-n)<minVal) {
minVal=abs(sq[i]-n);
minIdx=i;
}
}
cout<<sq[minIdx];
return 0;
}