【PAT甲级、乙级2020冬季】7-4 最近的斐波那契数 The Closest Fibonacci Number (20 分)

斐波那契数列 F​n​​ 的定义为:对 n≥0 有 F​n+2​​=F​n+1​​+F​n​​,初始值为 F​0​​=0 和 F​1​​=1。所谓与给定的整数 N 最近的斐波那契数是指与 N 的差之绝对值最小的斐波那契数。

本题就请你为任意给定的整数 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.

输入格式:

输入在一行中给出一个正整数 N(≤10​8​​)。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

猜你喜欢

转载自blog.csdn.net/WKX_5/article/details/114477733