PAT A 2020年冬 7-1 The Closest Fibonacci Number AC代码

该博客介绍了一个编程问题,即找到给定整数N最接近的斐波那契数。通过递归函数Fs实现了寻找过程,并在输入为305时,输出了最接近的斐波那契数233。代码使用C++编写,根据斐波那契数列的定义,当有两个解时,选择较小的那个作为答案。
摘要由CSDN通过智能技术生成

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 (≤108).

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>
using namespace std;
int N,ans1=0,ans2;
void Fs(int n,int f1,int f2){
	if(f1+f2>n){
		ans2=f1+f2;
		if(f2>=ans1) ans1=f2;
		return;
	}
	Fs(n,f2,f1+f2);
}
int main(){
	cin>>N;
	Fs(N,0,1);
	if(ans2-N>=N-ans1){
		printf("%d\n",ans1);
	}else{
		printf("%d\n",ans2);
	}
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值