PAT(甲级)2020年冬季考试 7-1 The Closest Fibonacci Number (20 分)

19 篇文章 0 订阅
17 篇文章 0 订阅
该博客介绍了如何找到给定整数N最接近的斐波那契数。输入包含一个正整数N(≤10^8),输出是最小绝对差的斐波那契数。如果存在多个解,应输出较小的那个。示例中,对于N=305,最接近的斐波那契数是233和377,两者与305的差距相同,但应输出较小的233。
摘要由CSDN通过智能技术生成

题目

The Fibonacci sequence F n F_n Fn​​ is defined by F n + 2 = F n + 1 + F n F_{n+2}=F_{n+1}+F_{n} Fn+2=Fn+1+Fn
​​ for n≥0, with F 0 = 0 F_{0}=0 F0=0and F 1 = 1 F_{1}=1 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 (≤ 1 0 8 10^8 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.

代码

#include<iostream>
using namespace std;
int a[1000000];
int fib(int n)
{
	if(n == 1)
		a[1] = 0;
	else if(n == 2)
		a[2] = 1;
    else if(a[n] != 0)
        return a[n];
	else
		a[n] = fib(n-1)+fib(n-2);
	return a[n];
}
int main()
{
	int n;
	scanf("%d",&n);
    fill(a,a+1000000,0);
	int i = 1;
	while(fib(i) <= n)
		i++;
	int A = a[i];
	int B = a[i-1];
	if(n-B <= A-n)
		cout << B;
	else
		cout << A;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43820008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值