当前位置:网站首页>【Day_07 0425】Fibonacci数列
【Day_07 0425】Fibonacci数列
2022-07-26 06:08:00 【安河桥畔】
Fibonacci数列
题目来源
牛客网:Fibonacci数列
题目描述
Fibonacci数列是这样定义的:
F[0] = 0
F[1] = 1
for each i ≥ 2: F[i] = F[i-1] + F[i-2]
因此,Fibonacci数列就形如:0, 1, 1, 2, 3, 5, 8, 13, …,在Fibonacci数列中的数我们称为Fibonacci数。给你一个N,你想让其变为一个Fibonacci数,每一步你可以把当前数字X变为X-1或者X+1,现在给你一个数N求最少需要多少步可以变为Fibonacci数。
输入描述
输入为一个正整数N(1 ≤ N ≤ 1,000,000)
输出描述
输出一个最小的步数变为Fibonacci数"
示例
输入
15
输出
2
思路分析
- 根据斐波那契数列的计算方法,使用迭代法计算,找到斐波那契数列中第一个大于n的数
- 计算这个斐波那契数和前一个斐波那契数哪个与n的距离近
代码展示
#include<iostream>
using namespace std;
int main()
{
int n=0;
cin>>n;
int first=1;
int second=1;
int third=1;
//找到第一个大于n的斐波那契数
while(third<n)
{
third=first+second;
first=second;
second=third;
}
int step=0;
//将较小的值赋给step
step=(third-n)>(n-first)?(n-first):(third-n);
cout<<step<<endl;
return 0;
}
边栏推荐
- Flex layout
- 某公司给每个工位装监控:只为看员工写代码?
- vagrant下载速度慢的解决方法
- JS的调用方式与执行顺序
- 递归处理——子问题
- Unity2d animator cannot create transition
- 【2023杰理科技提前批笔试题】~ 题目及参考答案
- Day110. Shangyitong: gateway integration, hospital scheduling management: Department list, statistics based on date, scheduling details
- L. Link with Level Editor I dp
- Leetcode:741. picking cherries
猜你喜欢

1.12 basis of Web Development

Implementation of PHP multitask second timer

Redis sentinel cluster setup

金仓数据库 KingbaseES SQL 语言参考手册 (10. 查询和子查询)

"Recursive processing of subproblems" -- judging whether two trees are the same tree -- and the subtree of another tree

Unity2D 动画器无法 创建过渡

The idea YML file code does not prompt the solution

Distributed | practice: smoothly migrate business from MYCAT to dble

日志收集分析平台搭建-1-环境准备

Embedded sharing collection 15
随机推荐
Webapi collation
知识沉淀一:架构师是做什么?解决了什么问题
1.12 Web开发基础
Modifiers should be declared in the correct order 修饰符应按正确的顺序声明
redis 哨兵集群搭建
[free and easy to use] holiday query interface
移动web
Matlab vector and matrix
某公司给每个工位装监控:只为看员工写代码?
JS的调用方式与执行顺序
Latex同时合并表格的多行多列
Binary sort tree (BST)~
数据库sql语言实战
Can you make a JS to get the verification code?
The time complexity of two recursive entries in a recursive function
Modifiers should be declared in the correct order
2022 National latest fire-fighting facility operator (Senior fire-fighting facility operator) simulation test questions and answers
VRRP protocol and experimental configuration
Kingbasees SQL language reference manual of Jincang database (10. Query and sub query)
漫谈软件缺陷管理的实践