查找最近的斐波那契数


30

我们都熟悉著名的Fibonacci序列,该序列0和开头1,每个元素都是前两个元素的和。以下是前几个术语(OEIS A000045):

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584

给定一个正整数,在以下规则下返回斐波那契数列的最接近的数字:

  • 所述最接近的斐波纳契数被定义为与该给定整数的最小绝对差斐波那契数。例如,34是最接近斐波那契数30,因为|34 - 30| = 4,这是比第二最接近的一个,更小21,为此|21 - 30| = 9

  • 如果给定的整数属于斐波那契数列,则最接近的斐波那契数就是它本身。例如,最接近的斐波那契数13恰好是13

  • 如果是平局,您可以选择输出两个都最接近输入的斐波那契数之一,也可以仅输出两个。例如,如果输入的是17,以下所有的都是有效的:211321, 13。如果您将它们都退回,请注明格式。

默认漏洞适用。您可以通过任何标准方法获取输入并提供输出。您的程序/函数最多只能处理10 8的值。


测试用例

输入->输出

1-> 1
3-> 3
4-> 3或5或3,5
6-> 5
7-> 8
11-> 13
17-> 13或21或13,21
63-> 55
101-> 89
377-> 377
467-> 377
500-> 610
1399-> 1597

计分

这是,因此每种语言中以字节为单位的最短代码胜出!



FWIW,是SO上的一些Python代码,可用于大输入有效地执行此操作,以及可用于计时各种算法的脚本。
下午17年

0是否被视为正整数?
艾力克斯·艾森哈特

@AlixEisenhardt号。正整数n表示n ≥ 1
Xcoder先生17年

Answers:


21

Python 2,43个字节

f=lambda n,a=0,b=1:a*(2*n<a+b)or f(n,b,a+b)

在线尝试!

对成对的连续斐波那契数进行迭代,(a,b)直到到达输入n小于中点的数为止(a+b)/2,然后返回a

编写为程序(47字节):

n=input()
a=b=1
while 2*n>a+b:a,b=b,a+b
print a

相同长度

f=lambda n,a=0,b=1:b/2/n*(b-a)or f(n,b,a+b)

15

Neim,5个字节

f𝐖𝕖S𝕔

说明:

f       Push infinite Fibonacci list
 𝐖                     93
  𝕖     Select the first ^ elements
        This is the maximum amount of elements we can get before the values overflow
        which means the largest value we support is 7,540,113,804,746,346,429
   S𝕔   Closest value to the input in the list

在最新版本的Neim中,这可以分为3个字节:

fS𝕔

由于对无限列表进行了重新设计,使其仅达到最大值。

在线尝试!


当那里有2个字符时,这5个字节如何?第一种和第二种解决方案之间有什么区别?
caird coinheringaahing

1
您是在计算字节还是字符?看起来前15个字节,后7个字节。
Nateowami

这可能具有某种自己的代码页,其中每个字符都是自己的字节,这意味着第一个是5个字节,第二个是3个字节。两者之间的区别在于,第一个选择了前93个元素手册,而第二个版本在较新版本中自动选择了int大小语言可以处理的最高值
RomanGräf17年

1
@cairdcoinheringaahing我经常遇到人们看不到我程序的问题。屏幕快照
Okx

1
@Okx哦,好的,有趣,我不会猜到。
Nateowami


8

R70 67 64 62 60字节

-2个字节,感谢djhurio!

多亏了djhurio -2个字节 (男孩可以打高尔夫球!)

F=1:0;while(F<1e8)F=c(F[1]+F[2],F);F[order((F-scan())^2)][1]

由于我们只需要处理不超过的值10^8,因此可以使用。

在线尝试!

n从stdin 读取。的while环路生成Fibonacci数F(按递减次序); 如果出现平局,则返回较大的。这将触发许多警告,因为while(F<1e8)仅对F带有警告的第一个元素的语句求值

最初,我使用的F[which.min(abs(F-n))]是朴素的方法,但是@djhurio建议使用,(F-n)^2因为排序将是等效的,而order不是which.minorder虽然返回索引的排列以使其输入按升序排列,所以最后我们只需要[1]获取第一个值即可。

更快的版本:

F=1:0;n=scan();while(n>F)F=c(sum(F),F[1]);F[order((F-n)^2)][‌​1]

仅存储最后两个斐波那契数


1
好东西。-2个字节F=1:0;n=scan();while(n>F)F=c(F[1]+F[2],F);F[order((F-n)^2)][1]
djhurio'7

1
以及具有相同字节数的快速版本F=1:0;n=scan();while(n>F)F=c(sum(F),F[1]);F[order((F-n)^2)][1]
djhurio '17

1
@djhurio很好!非常感谢你。
朱塞佩

1
我喜欢这个。-2个字节再次F=1:0;while(F<1e8)F=c(F[1]+F[2],F);F[order((F-scan())^2)][1]
djhurio '17

使用内建函数生成纤维的时间更短:numbers::fibonacci(x<-scan(),T)
JAD

6

JavaScript(ES6),41个字节

f=(n,x=0,y=1)=>y<n?f(n,y,x+y):y-n>n-x?x:y
<input type=number min=0 value=0 oninput=o.textContent=f(this.value)><pre id=o>0

按偏好取整。


几乎与我正在使用的版本相同。至少您没有使用相同的变量名,否则我会被吓坏了。
Grax32

@Grax Huh,现在您提到它,Business Cat击败了我……
Neil

(好吧,几乎……我使我的版本可以使用0,因为为什么不呢?)
Neil

f=(n,x=0,y=1)=>x*(2*n<x+y)||f(n,y,x+y)由于您不必使用0,因此您可以打更多的高尔夫球。
Alix Eisenhardt

6

果冻9 7个字节

-2个字节,感谢@EriktheOutgolfer

‘RÆḞạÐṂ

在线尝试!

欢迎打高尔夫球:)。接受一个int作为输入并返回一个int-list。

            ' input -> 4
‘           ' increment -> 5
 R          ' range -> [1,2,3,4,5]
  ÆḞ        ' fibonacci (vectorizes) -> [1,1,2,3,5,8]
     ÐṂ     ' filter and keep the minimum by:
    ạ       ' absolute difference -> [3,3,2,1,1,4]
            ' after filter -> [3,5]


@EriktheOutgolfer是这样的:“如果考虑的话,有一种方法可以解决”,或者例如“如果您只是退格,它们仍然可以工作”?
nmjcman101

如“规则允许”。:P
暴民埃里克(Erik the Outgolfer)'17

啊。谢谢!(填充文本)
nmjcman101 '17


5

x86-64机器码,24字节

31 C0 8D 50 01 92 01 C2 39 FA 7E F9 89 D1 29 FA 29 C7 39 D7 0F 4F C1 C3

上面的代码字节在64位x86机器代码中定义了一个函数,该函数查找与指定输入值最接近的斐波那契数, n

该函数遵循System V AMD64调用约定(Gnu / Unix系统上的标准),从而唯一的参数(n)在EDI寄存器中传递,结果在EAX寄存器中返回。

非高尔夫装配助记符:

; unsigned int ClosestFibonacci(unsigned int n);
    xor    eax, eax        ; initialize EAX to 0
    lea    edx, [rax+1]    ; initialize EDX to 1

  CalcFib:
    xchg   eax, edx        ; swap EAX and EDX
    add    edx, eax        ; EDX += EAX
    cmp    edx, edi
    jle    CalcFib         ; keep looping until we find a Fibonacci number > n

    mov    ecx, edx        ; temporary copy of EDX, because we 'bout to clobber it
    sub    edx, edi
    sub    edi, eax
    cmp    edi, edx
    cmovg  eax, ecx        ; EAX = (n-EAX > EDX-n) ? EDX : EAX
    ret

在线尝试!

该代码基本上分为三部分:

  • 第一部分非常简单:它只是初始化我们的工作寄存器。EAX设置为0,并EDX设置为1。
  • 下一部分是一个循环,该循环迭代地计算输入值两侧的斐波那契数n。这段代码基于我以前对Fibonacci的减法实现,但是……嗯……不是减法。:-)特别是,它使用相同的技巧来计算两个变量的斐波那契数-这里是EAXEDX寄存器。这种方法在这里非常方便,因为它为我们提供了相邻的斐波那契数。候选人可能小于 n被保持在EAX,而候选者可能大于 n保留的。EDX。我为能够在此循环内编写代码如此紧密而感到自豪(更让我高兴的是,我重新发现了它,直到后来才意识到它与上面链接的减法答案有多么相似)。

  • 一旦我们在EAX和中都有可用的候选斐波那契值EDX,就可以从概念上简单地弄清楚哪个值(就绝对值而言)更接近n。实际上取绝对值会花费方式太多字节,所以我们只是做了一系列的减法。倒数第二条条件移动指令右侧的注释恰当地解释了此处的逻辑。它要么EDX移入EAX,要么移开EAX,这样当函数启动时RET,最接近的Fibonacci数将返回EAX

如果是平局,则返回两个候选值中较小的一个,因为我们使用了CMOVG而不是进行CMOVGE选择。如果您更喜欢其他行为,则这是微不足道的更改。但是,返回两个值都不是入门。请只取一个整数结果!


NASM清单非常适合代码高尔夫球的答案,因为它们将机器代码字节与原始注释源之间的压缩程度比较紧凑。nasm foo.asm -l /dev/stdout | cut -b -28,$((28+12))-在最近的答案中,我曾经在机器代码和源代码之间修剪一些列。
彼得·科德斯

1
在32位代码中,使用xor eax,eax/ cdq/ 只能在4个字节而不是5个字节中获得eax = 0和edx = 1 inc edx。因此,您可以制作一个节省了一个字节的32位自定义呼叫约定版本。
彼得·科德斯

我曾经这样做过,@ Peter,但是由于提交内容是“汇编”或“机器代码”,所以这里存在很多困惑。显然,一些有经验的用户认为这是有区别的,因此反对我计算使用汇编助记符给出的答案的机器代码字节数。自然,我认为这很愚蠢,因为“汇编”只是机器字节的助记符表示形式,但我对此表示反对。我发现单独的演示文稿可以减少摩擦,即使我个人也不喜欢它。
科迪·格雷

另一个技巧是很好-谢谢。我应该想到的是,我cdq在代码高尔夫球的答案中使用了很多。不需要自定义调用约定。我通常将Microsoft __fastcall调用约定用于32位代码。这样做的好处是,GCC支持带有注释,因此您仍然可以使用每个人都希望看到的TIO服务。
科迪·格雷

嗯,是的,任何旧的调用约定的约定都可以为您工作。我最近的代码高尔夫答案需要edi/中的esifor lodsb/ 指针stosb,只有x86-64 SysV可以做到这一点(有趣的事实:出于这个原因,因为某些函数将其args传递给memset / memcpy,而我猜当时的gcc喜欢内联字符串操作)。
彼得·科德斯

4

的PowerShell80 74字节

param($n)for($a,$b=1,0;$a-lt$n;$a,$b=$b,($a+$b)){}($b,$a)[($b-$n-gt$n-$a)]

(在线尝试!暂时无响应)

Iterative solution. Takes input $n, sets $a,$b to be 1,0, and then loops with Fibonacci until $a is larger than the input. At that point, we index into ($b,$a) based on Boolean of whether the difference between the first element and $n is greater than between $n and the second element. That's left on the pipeline, output is implicit.


4

JavaScript (ES6), 67 bytes

f=(n,k,y)=>(g=k=>x=k>1?g(--k)+g(--k):k)(k)>n?x+y>2*n?y:x:f(n,-~k,x)

Test cases


4

JavaScript (Babel Node), 41 bytes

f=(n,i=1,j=1)=>j<n?f(n,j,j+i):j-n>n-i?i:j

Based on ovs's awesome Python answer

Try it online!

Ungolfed

f=(n,i=1,j=1)=> // Function f: n is the input, i and j are the most recent two Fibonacci numbers, initially 1, 1
 j<n?           // If j is still less than n
  f(n,j,j+i)    //  Try again with the next two Fibonacci numbers
 :              // Else:
  j-n>n-i?i:j   //  If n is closer to i, return i, else return j

This was commented on my answer but it would make it stop working for 0 (not that it needs to; I just want it to): f=(n,i=1,j=1)=>n+n<i+j?i:f(n,j,j+i)
Neil

4

Python, 74 bytes

import math
r=5**.5
p=r/2+.5
lambda n:round(p**int(math.log(n*2*r,p)-1)/r)

Try it online!

How it works

For all k ≥ 0, since |φk/√5| < 1/2, Fk = φk/√5 + φk/√5 = round(φk/√5). So the return value switches from Fk − 1 to Fk exactly where k = logφ(n⋅2√5) − 1, or n = φk + 1/(2√5), which is within 1/4 of Fk + 1/2 = (Fk − 1 + Fk)/2.


Damn, I knew something like this had to be possible. Well done! (+1)
SteamyRoot




3

Python 3, 103 bytes

import math
def f(n):d=5**.5;p=.5+d/2;l=p**int(math.log(d*n,p))/d;L=[l,p*l];return round(L[2*n>sum(L)])

Try it online!

Sadly, had to use a def instead of lambda... There's probably much room for improvement here.

Original (incorrect) answer:

Python 3, 72 bytes

lambda n:r(p**r(math.log(d*n,p))/d)
import math
d=5**.5
p=.5+d/2
r=round

Try it online!

My first PPCG submission. Instead of either calculating Fibonacci numbers recursively or having them predefined, this code uses how the n-th Fibonacci number is the nearest integer to the n-th power of the golden ratio divided by the root of 5.


Nice job! Welcome to PPCG :)
musicman523

To fairly calculate the byte count of your code I think you need to assign the lambda, as shown in the other Python answers. However, this algorithm doesn't always work correctly for n in range(1, 1+10**8). Eg, n=70 returns 89, but it should return 55. Here are the n values < 120 that it gives wrong answers for: (27, 44, 70, 71, 114, 115, 116). For testing purposes, you may like to use the nearest_fib_PM2R function I linked in my comment on the question.
PM 2Ring

@PM2Ring You're right, I made a stupid mistake... I now have a correct solution, but with a lot more bytes. As for the lambda, I believe you're wrong. I believe the answers assigning lambda only do so because they use recursion. The other Python 3 answers doesn't assign the first lambda, for example.
SteamyRoot

3

Taxi, 2321 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:n 1 l 1 l.0 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 l.Pickup a passenger going to Bird's Bench.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.[a]Pickup a passenger going to Rob's Rest.Pickup a passenger going to Magic Eight.Go to Bird's Bench:n 1 r 2 r 1 l.Go to Rob's Rest:n.Go to Trunkers:s 1 l 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Trunkers.Pickup a passenger going to Magic Eight.Go to Zoom Zoom:n.Go to Trunkers:w 3 l.Go to Magic Eight:e 1 r.Switch to plan "b" if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:w 1 r.Go to Rob's Rest:w 1 l 1 r 1 l 1 r 1 r.Pickup a passenger going to Cyclone.Go to Bird's Bench:s.Pickup a passenger going to Addition Alley.Go to Cyclone:n 1 r 1 l 2 l.Pickup a passenger going to Addition Alley.Pickup a passenger going to Bird's Bench.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Switch to plan "a".[b]Go to Trunkers:w 1 l.Pickup a passenger going to Cyclone.Go to Bird's Bench:w 1 l 1 r 1 l.Pickup a passenger going to Cyclone.Go to Rob's Rest:n.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to What's The Difference.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 l.Pickup a passenger going to Magic Eight.Go to Sunny Skies Park:e 1 r 1 l.Go to Cyclone:n 1 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to What's The Difference.Go to Sunny Skies Park:n 1 r.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 r 1 l.Pickup a passenger going to Magic Eight.Go to Magic Eight:e 1 r 2 l 2 r.Switch to plan "c" if no one is waiting.Go to Sunny Skies Park:w 1 l 1 r.Pickup a passenger going to The Babelfishery.Go to Cyclone:n 1 l.Switch to plan "d".[c]Go to Cyclone:w 1 l 2 r.[d]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 2 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!
Try it online with comments!

Un-golfed with comments:

[ Find the Fibonacci number closest to the input ]
[ Inspired by: https://codegolf.stackexchange.com/q/133365 ]


[ n = STDIN ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Trunkers.
Go to Trunkers: north 1st left 1st left.


[ Initialize with F0=0 and F1=1 ]
0 is waiting at Starchild Numerology.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 2nd left.
Pickup a passenger going to Bird's Bench.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 1st right 4th left.


[ For (i = 1; n > F(i); i++) { Store F(i) at Rob's Rest and F(i-1) at Bird's Bench } ]
[a]
Pickup a passenger going to Rob's Rest.
Pickup a passenger going to Magic Eight.
Go to Bird's Bench: north 1st right 2nd right 1st left.
Go to Rob's Rest: north.
Go to Trunkers: south 1st left 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 2nd right.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Magic Eight.
Go to Zoom Zoom: north.
Go to Trunkers: west 3rd left.
Go to Magic Eight: east 1st right.
Switch to plan "b" if no one is waiting.

[ n >= F(i) so iterate i ]
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: west 1st right.
Go to Rob's Rest: west 1st left 1st right 1st left 1st right 1st right.
Pickup a passenger going to Cyclone.
Go to Bird's Bench: south.
Pickup a passenger going to Addition Alley.
Go to Cyclone: north 1st right 1st left 2nd left.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Bird's Bench.
Go to Addition Alley: north 2nd right 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left.
Switch to plan "a".


[b]
[ F(i) > n which means n >= F(i-1) and we need to figure out which is closer and print it]
Go to Trunkers: west 1st left.
Pickup a passenger going to Cyclone.
Go to Bird's Bench: west 1st left 1st right 1st left.
Pickup a passenger going to Cyclone.
Go to Rob's Rest: north.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st left 1st left 2nd left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to What's The Difference.
[ Passengers:n, n, F(i-1) ]
Go to What's The Difference: north 1st left.
Pickup a passenger going to Magic Eight.
[ Passengers:n, n-F(i-1) ]
Go to Sunny Skies Park: east 1st right 1st left.
Go to Cyclone: north 1st left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to What's The Difference.
[ Passengers: n-F(i-1), F(i-1), F(i) ]
Go to Sunny Skies Park: north 1st right.
Pickup a passenger going to What's The Difference.
[ Passengers: n-F(i-1), F(i), n ]
Go to What's The Difference: north 1st right 1st left.
[ Passengers: n-F(i-1), F(i)-n ]
Pickup a passenger going to Magic Eight.
Go to Magic Eight: east 1st right 2nd left 2nd right.
Switch to plan "c" if no one is waiting.

[ If no one was waiting, then {n-F(i-1)} < {F(i)-n} so we return F(i-1) ]
Go to Sunny Skies Park: west 1st left 1st right.
Pickup a passenger going to The Babelfishery.
Go to Cyclone: north 1st left.
Switch to plan "d".

[c]
[ Otherwise {n-F(i-1)} >= {F(i)-n} so we return F(i) ]
[ Note: If we didn't switch to plan c, we still pickup F(i) but F(i-1) will be the *first* passenger and we only pickup one at The Babelfishery ]
[ Note: Because of how Magic Eight works, we will always return F(i) in the event of a tie ]
Go to Cyclone: west 1st left 2nd right.
[d]
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 2nd right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.

2

Python 3, 84 bytes

lambda k:min(map(f,range(2*k)),key=lambda n:abs(n-k))
f=lambda i:i<3or f(i-1)+f(i-2)

Try it online!

It may work, but it's certainly not fast...

Outputs True instead of 1, but in Python these are equivalent.


2

dc, 52 bytes

si1d[dsf+lfrdli>F]dsFxli-rlir-sdd[lild-pq]sDld<Dli+p

Try it online!

Takes input at run using ?

Edited to assume top of stack as input value, -1 byte.

Input is stored in register i. Then we put 1 and 1 on the stack to start the Fibonacci sequence, and we generate the sequence until we hit a value greater than i. At this point we have two numbers in the Fibonacci sequence on the stack: one that is less than or equal to i, and one that is greater than i. We convert these into their respective differences with i and then compare the differences. Finally we reconstruct the Fibonacci number by either adding or subtracting the difference to i.

Oops, I was loading two registers in the wrong order and then swapping them, wasting a byte.


Functions are allowed.
CalculatorFeline

Thanks, I repeatedly missed that in the challenge's text.
brhfl

2

C# (.NET Core), 63 56 bytes

-1 byte thanks to @Neil

-6 bytes thanks to @Nevay

n=>{int a=0,b=1;for(;b<n;a=b-a)b+=a;return n-a>b-n?b:a;}

Try it online!


Does for(;b<n;a=b,b+=c)c=a; save a byte?
Neil

You can remove c by using b+=a,a=b-a (should save 6 bytes).
Nevay


2

Hexagony, 37 bytes

?\=-${&"*.2}+".|'=='.@.&}1.!_|._}$_}{

Try it online!

ungolfed:

   ? \ = - 
  $ { & " * 
 . 2 } + " .
| ' = = ' . @
 . & } 1 . !
  _ | . _ }
   $ _ } { 

Broken down:

start:
? { 2 ' * //set up 2*target number
" ' 1     //initialize curr to 1

main loop:
} = +     //next + curr + last
" -       //test = next - (2*target)
branch: <= 0 -> continue; > 0 -> return

continue:
{ } = &   //last = curr
} = &     //curr = next


return:
{ } ! @   //print last

Like some other posters, I realized that when the midpoint of last and curr is greater than the target, the smaller of the two is the closest or tied for closest.

The midpoint is at (last + curr)/2. We can shorten that because next is already last + curr, and if we instead multiply our target integer by 2, we only need to check that (next - 2*target) > 0, then return last.




1

Java 7, 244 234 Bytes

 String c(int c){for(int i=1;;i++){int r=f(i);int s=f(i-1);if(r>c && s<c){if(c-s == r-c)return ""+r+","+s;else if(s-c > r-c)return ""+r;return ""+s;}}} int f(int i){if(i<1)return 0;else if(i==1)return 1;else return f(i-2)+f(i-1);}

Why don't you use Java 8 and turn this into a lambda? You can also remove static if you want to stick with Java 7.
Okx

You have two errors in your code (r>c&&s<c should be r>=c&&s<=c, s-c should be c-s), You could remove not required whitespace, use int f(int i){return i<2?i:f(--i)+f(--i);}, use a single return statement with ternary operator in c and remove the special handling for c-s==r-c as returning either value is allowed.
Nevay

@Nevay I don't see the error, I've tested it without fails
0x45


1

Pyke, 6 bytes

}~F>R^

Try it online!

}      -    input*2
 ~F    -   infinite list of the fibonacci numbers
   >   -  ^[:input]
    R^ - closest_to(^, input)


1

Perl 6, 38 bytes

{(0,1,*+*...*>$_).sort((*-$_).abs)[0]}

Test it

{   # bare block lambda with implicit parameter 「$_」

  ( # generate Fibonacci sequence

    0, 1,  # seed the sequence
    * + *  # WhateverCode lambda that generates the rest of the values
    ...    # keep generating until
    * > $_ # it generates one larger than the original input
           # (that larger value is included in the sequence)

  ).sort(           # sort it by
    ( * - $_ ).abs  # the absolute difference to the original input
  )[0]              # get the first value from the sorted list
}

For a potential speed-up add .tail(2) before .sort(…).

In the case of a tie, it will always return the smaller of the two values, because sort is a stable sort. (two values which would sort the same keep their order)


1

Pyth, 19 bytes

JU2VQ=+Js>2J)hoaNQJ

Try it here

Explanation

JU2VQ=+Js>2J)hoaNQJ
JU2                  Set J = [0, 1].
   VQ=+Js>2J)        Add the next <input> Fibonacci numbers.
              oaNQJ  Sort them by distance to <input>.
             h       Take the first.

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.