最も近いフィボナッチ数を見つける


30

我々は、すべての有名に精通しているフィボナッチ数列で始まり、0そして1、各要素は、前の2の合計です。以下に、最初のいくつかの用語を示します(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。これは、、、が2番目に近いもの、、の21ためにのためです|21 - 30| = 9

  • 指定された整数がフィボナッチ数列に属する場合、最も近いフィボナッチ数はそれ自体です。たとえば、最も近いフィボナッチ数13はになり13ます。

  • 同点の場合、入力に最も近いフィボナッチ数のいずれかを出力するか、両方を出力するかを選択できます。たとえば、入力がの場合、17次のすべてが有効です:2113または21, 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コードです。
PM 2Ring

0は正の整数と見なされますか?
アリックスアイゼンハルト

@AlixEisenhardtいいえ。正の整数はをn意味しn ≥ 1ます。
ミスターXcoder

回答:


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

ニーム、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バイトはどうですか?そして、最初のソリューションと2番目のソリューションの違いは何ですか?
コイナーリンガーリング

1
バイトまたは文字をカウントしていますか?最初は15バイトで、2番目は7バイトです。
ナテオワミ

これはおそらく、各文字が独自のバイトである独自のコードページを持っています。つまり、最初の文字は5バイト、2番目は3バイトです。両者の違いは、最初のものは、新しいバージョンに自動的に言語INTサイズを扱うことができる可能な限り最高の値を選択する第二snipetながらマニュアル第93の要素を選択することである
ローマンGRAF

1
@cairdcoinheringaahing私は自分のプログラムを見ることができない人々にしばしば問題を抱えてきました。スクリーンショット
Okx

1
@Okxああ、興味深い、私は推測しなかっただろう。
なとわみ


8

R70 67 64 62 60バイト

djhurioのおかげで-2バイト!

-djhurioのおかげでさらに2バイト (少年はゴルフができます!)

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

までの値を処理するだけでよいため10^8、これは機能します。

オンラインでお試しください!

nstdinから読み取ります。whileループにおけるフィボナッチ数生成F(降順に)を、同点の場合、大きい方が返されます。これにより、いくつかの警告がトリガーされます。while(F<1e8)ある最初の要素のステートメントのみを評価するされFます。

もともと私F[which.min(abs(F-n))]は単純なアプローチを使用していましたが(F-n)^2、順序は同等であり、order代わりに@djhurioが提案しましたwhich.minorderただし、入力を昇順にするためにインデックスの順列を返します。したがって、[1]、最後に最初の値のみを取得ます。

より速いバージョン:

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

最後の2つのフィボナッチ数のみを保存します


1
良いですね。-2バイトF=1:0;n=scan();while(n>F)F=c(F[1]+F[2],F);F[order((F-n)^2)][1]
-djhurio

1
同じバイト数の高速バージョンF=1:0;n=scan();while(n>F)F=c(sum(F),F[1]);F[order((F-n)^2)][1]
-djhurio

1
@djhurioいいね!どうもありがとうございました。
ジュゼッペ

1
私はこれが好き。-2バイト再びF=1:0;while(F<1e8)F=c(F[1]+F[2],F);F[order((F-scan())^2)][1]
-djhurio

fibnumsを生成するための組み込みを短くされた使用: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、あなたはそれについて言及します、ビジネスキャットは私にそれを打ちました...-
ニール

(まあ、ほとんど...私は0で動作するバージョンを作成しました。理由は何ですか?)
ニール

f=(n,x=0,y=1)=>x*(2*n<x+y)||f(n,y,x+y)0で作業する必要はないので、もう少しゴルフをすることができます。
アリックスアイゼンハルト

6

ゼリー9 7バイト

@EriktheOutgolferのおかげで-2バイト

‘RÆḞạÐṂ

オンラインでお試しください!

ゴルフのヒントを歓迎します:)。入力にintを取り、intリストを返します。

            ' 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
エリックOutgolfer

あ。ありがとうございました!(フィラーテキスト)
nmjcman101


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

オンラインでお試しください!

コードは基本的に3つの部分に分かれています。

  • 最初の部分は非常に単純です。作業レジスタを初期化するだけです。EAX0に設定され、EDX設定され、1に設定されます。
  • 次の部分は、入力値の両側のフィボナッチ数を繰り返し計算するループですn。このコードは、以前の減算付きフィボナッチの実装に基づいていますが、…ええと…減算ではありません。:-)特に、2つの変数を使用してフィボナッチ数を計算する同じトリックを使用します。ここでは、これらはEAXEDXレジスタです。このアプローチは非常に、フィボナッチ数が隣接するため、ここで便利です。潜在的により小さい 候補nはに保持されEAX、潜在的により大きい 候補nは保持されていますEDX。このループ内でコードを作成できたことを非常に誇りに思っています(さらに、それを独立して再発見したことをさらにくすぐった後、上記のリンクされた減算の答えにどれほど似ているかを実感しました)。

  • 候補フィボナッチ値がEAXEDXで利用可能になると、どちらが(絶対値に関して)に近いかを把握するという概念的に単純な問題になりnます。実際にはコストがかかる絶対値をとる方法我々だけ減算の一連の操作を行うので、あまりにも多くのバイトを。最後から2番目の条件付き移動命令の右側にあるコメントは、このロジックを適切に説明しています。このどちらかの移動EDXEAX、または葉EAXのみで、その機能のときにRET壷は、最寄りのフィボナッチ数はで返されますEAX

同点の場合、選択の代わりに使用したため、2つの候補値のうち小さい方が返されます。他の動作を好む場合、それは些細な変更です。ただし、両方の値を返すことはスターターではありません。整数の結果は1つだけにしてください!CMOVGCMOVGE


NASMのリストはcodegolfの回答に適しています。これは、マシンコードのバイトと元のコメントソースを多少コンパクトに混在させるためです。私が使用しnasm foo.asm -l /dev/stdout | cut -b -28,$((28+12))-、最近の回答でマシンコードとソースとの間にいくつかの列をトリミングします。
ピーターコーデス

1
32ビットコードでは、xor eax,eax/ cdq/を使用して、eax = 0およびedx = 1を5ではなく4バイトで取得できますinc edx。したがって、バイトを保存した32ビットのカスタム呼び出し規約バージョンを作成できます。
ピーターコーデス

以前は@Peterを使用していましたが、ここでは、「アセンブリ」または「マシンコード」にある提出物に関して多くの混乱があります。どうやら経験豊富なユーザーの一部は違いがあると主張しており、アセンブリニーモニックを使用して提示される回答のマシンコードのバイト数をカウントすることに反対しています。当然、「アセンブリ」はマシンバイトのニーモニック表現にすぎないため、これは馬鹿げていると思いますが、私は投票しました。個人的には好きではありませんが、別のプレゼンテーションのほうが摩擦が少ないことがわかりました。
コーディグレー

もう1つのトリックは素晴らしいです。ありがとう。私はそれを考えるべきでした、私cdqはコードゴルフの答えで多くを使います。カスタム呼び出し規約は必要ありません。通常__fastcall、32ビットコードにはMicrosoftの呼び出し規則を使用します。これの良い点は、アノテーションを使用してGCCでサポートされているため、誰もが見たいTIOサービスを引き続き使用できることです。
コーディグレー

ああ、古いレジスター呼び出し規約はあなたのために機能します。私の最新のcodegolfの答えはedi/のesiためのlodsb/のポインタを必要stosbとし、x86-64 SysVのみがそれを行います(楽しい事実:その理由のために、いくつかの関数は引数をmemset / memcpyに渡し、gccが好きだったと思うのでインライン文字列opsへ)。
ピーターコーデス

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)]

(オンラインで試してください!一時的に応答しません)

反復ソリューション。入力を受け取り$n、に設定$a,$bし、入力より大きくなる1,0までフィボナッチでループし$aます。その時点で($b,$a)、最初の要素との間の差が2番目の要素との$n間の差より大きいかどうかのブール値に基づいてインデックスを作成し$nます。それはパイプラインに残っており、出力は暗黙的です。


4

JavaScript(ES6)、67バイト

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)

テストケース


4

JavaScript(Babelノード)、41バイト

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

ovsのすばらしいPythonの回答に基づく

オンラインでお試しください!

非ゴルフ

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

すべてのためのk以来≥0、|φ - K /√5| <1/2、FのKK /√5+φ - K /√5= ROUND(φ K /√5)。戻り値から切り替えるようにFのK - 1までのF kの正確な場所、K =ログφN ⋅2√5) - 1、またはNK + 1の1/4以内である/(2√5)F k + 1/2 =(F k − 1 + F k)/ 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

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.

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.