The Fibonacci sequence Fn is defined as: for n≥0 there is Fn+2=Fn+1+Fn, the initial value is F0= 0 and F1=1. The so-called Fibonacci number closest to the given integer N is the Fibonacci number with the smallest absolute value of the difference with N.
This question asks you to find the nearest Fibonacci number for any given integer 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.
Input format:
Enter a positive integer N (≤108) in one line. For each case, print the closest Fibonacci number. If the solution is not unique, output the smallest one.
Output format:
Output the Fibonacci number closest to N in one line. If the solution is not unique, output the smallest number. For each case, print the closest Fibonacci number. If the solution is not unique, output the smallest one.
Input sample:
305
Sample output:
233
Sample explanation
Some Fibonacci numbers are {0, 1, 1, 2, 3, 5, 8, 12, 21, 34, 55, 89, 144, 233, 377, 610, ... }. It can be seen that the distances between 233 and 377 to 305 are the minimum value 72, and the smaller solution should be output.
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.
Code:
#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 minutes AC