[PAT Class A, Class B Winter 2020] 7-4 The Closest Fibonacci Number (20 points)

The Fibonacci sequence  F​n​​ is defined as: for n≥0 there is F​n+2​​=F​n+1​​+F​n​​, the initial value is F​0​​= 0 and F​1​​=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 F​n​​ 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 format:

Enter a positive integer N (≤10​8​​) 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

Guess you like

Origin blog.csdn.net/WKX_5/article/details/114477733