斐波那契数列 Fn 的定义为:对 n≥0 有 Fn+2=Fn+1+Fn,初始值为 F0=0 和 F1=1。所谓与给定的整数 N 最近的斐波那契数是指与 N 的差之绝对值最小的斐波那契数。
本题就请你为任意给定的整数 N 找出与之最近的斐波那契数。
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.
输入格式:
输入在一行中给出一个正整数 N(≤108)。For each case, print the closest Fibonacci number. If the solution is not unique, output the smallest one.
输出格式:
在一行输出与 N 最近的斐波那契数。如果解不唯一,输出最小的那个数。For each case, print the closest Fibonacci number. If the solution is not unique, output the smallest one.
输入样例:
305
输出样例:
233
样例解释
部分斐波那契数列为 { 0, 1, 1, 2, 3, 5, 8, 12, 21, 34, 55, 89, 144, 233, 377, 610, ... }。可见 233 和 377 到 305 的距离都是最小值 72,则应输出较小的那个解。
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.
代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
cin>>n;
int f0=0,f1=1;
while(f1<=n){
int k=f0;
f0=f1;
f1=k+f0;
}
if(abs(n-f0)<=abs(n-f1)) cout<<f0;
else cout<<f1;
return 0;
}
10分钟AC