g | x | w | all
Bytes Lang Time Link
043AWK250821T125504Zxrs
041Desmos230819T012817Zfwoosh
071C gcc170614T183109Zcleblanc
005Thunno 2230611T140724ZThe Thon
077D220924T192621ZThe Zip
036Prolog SWI220924T174401ZnaffetS
087Bash220826T133837Zfipsbox
046brev220826T072258ZSandra
004Vyxal r220709T202823ZDeadcode
034dc220811T012733ZBenji
161Regex ECMAScript190121T085940ZDeadcode
259CSASM v2.1.2.3210321T034523Zabsolute
037Java JDK170615T094510ZOlivier
026k4190827T090358Zscrawl
014Brachylog190827T074559ZUnrelate
004MathGolf190308T114827Zmaxb
nanZX81 BASIC ~94 tokenized BASIC bytes171218T143927ZShaun Be
008cQuents170726T155710ZStephen
134Alchemist190126T004249Zბიმო
040Ruby180122T174442ZAsone Tu
051C# .NET Core190122T235206Zdana
022><>170616T083545ZSok
048[Python 3]180122T020523ZSandeep
036C170913T233900Zpeterh
002Neim170614T170001ZOkx
007Japt170705T170405ZShaggy
054Common Lisp170615T123547ZRenzo
059Python 3170705T132542Zwrymug
050Python 3170615T105545Z0xffcour
031R170616T095754Zrturnbul
nan><>170615T120545ZEmigna
057D170616T084723Zbtd
040Java170616T072504ZDavid Co
022Cubix170615T220438ZMickyT
002Actually170615T200929ZDJMcMayh
061AWK170614T202147ZRobert B
029Julia 0.4170614T181751ZMagic Oc
044Javascript ES6 without the ** operator170615T162037ZHP Willi
083><>170614T195855ZAGourd
072Swift170615T123242ZCaleb Kl
044PHP170614T171555ZJör
00705AB1E170614T170405ZMagic Oc
00705AB1E170614T173433ZErik the
094Java 8170615T081056ZKevin Cr
031Haskell170615T080120ZLaikoni
024QBIC170615T070655Zsteenber
030Mathematica170615T065909Zalephalp
032Pari/GP170614T171156Zalephalp
016MATL170615T003618ZDrQuariu
020k170614T231827Zzgrep
044Python 2170614T170950Zmbomb007
089Javascript170614T212658ZDaffy
061Clojure170614T211133ZNikoNyrh
037CJam170614T210222ZEsolangi
050C gcc170614T210218ZHagen vo
040R170614T180103ZJAD
017Dyalog APL170614T172154ZUriel
109C#170614T192814ZKaito Ki
006Jelly170614T171259ZJonathan
037Mathematica170614T170552ZZaMoC
023Retina170614T183107ZMartin E
037Groovy170614T174943ZMagic Oc
078JS ES6170614T181042Zuser7070
057JS ES6170614T181911Zuser7070
033Mathematica170614T175244ZZaMoC
005Jelly170614T172246ZChristia
066Swift170614T173417ZMr. Xcod
003Seriously170614T173243Zsporkl
034JavaScript ES6170614T172307ZETHprodu
048Python 3170614T171618ZDennis
023Perl 6170614T171333ZSean

AWK, 43 bytes

$0=(5*$1^2+4)^.5!~/\./||(5*$1^2-4)^.5!~/\./

Attempt This Online!

Prints 1 for truthy or nothing for falsey.

Slightly longer version will print 0 for falsey:

1,$0=(5*$1^2+4)^.5!~/\./||(5*$1^2-4)^.5!~/\./

Attempt This Online!

Desmos, 58 41 bytes

-17 bytes thanks to Aiden Chow!

f(n)=0^{mod((5nn+[4,0^n4-4])^{.5},1).min}

Try it on Desmos!

Checks if either \$5n^2+4\$ or \$5n^2-4\$ is a perfect square.

C (gcc), 76, 52, 71 bytes,

Thanks GPT4 with a bit of prompt engineering

Way off, just plain wrong, good for the three test inputs but...

GTP4 after some serious tutoring finally 58 bytes

f(n,a,b){for(a=b=1;a<n;b+=a,a=b-a);return n==a||n==b||!n;}
F(n){return n<2?n:F(n-1)+F(n-2);}i;f(n){for(i=0;F(i)<n;i++);int x=F(i)==n;}
f(n,i,j){for(i=0,j=1;j<n;i=j,j+=i);return j==n||!n;}

Try it online!

Thunno 2, 5 bytes

ĖÆF$Ƈ

Attempt This Online!

Explanation

ĖÆF$Ƈ  # Implicit input
Ė      # Push [0..input]
 ÆF    # For each n, get the nth Fibonacci number
       # (starting at 0->0, 1->1, 2->1, etc.)
   $Ƈ  # Is the input in this list?
       # Implicit output

D, 98 79 bytes 77 bytes

-19 bytes: changed square number algorithm (which also had the side effect of not needing import std;) and realized the non-UFCS way was 1 byte shorter

golfed:

int p(real z){return z^^.5%1==0;}int f(int z){return p(5*z*z+4)||p(5*z*z-4);}

readable:

int p(real z){
    return z^^.5%1==0
}
int f(int z){
    return p(5*z*z+4)||p(5*z*z-4);
}

where f is the function that tests if a number is a fibonacci number.

This uses the fact that a positive integer z is a Fibonacci number if and only if one of 5z^2 + 4 or 5z^2 − 4 is a perfect square. wikipedia

Also real instead of float for one less byte, and returning an int instead of bool to save another byte (since ints are truthy if they're nonzero, and D implicitly casts expressions to the function's return value if possible, in this case casting a bool to an int).

There's probably some way to avoid having the extra function p (used to check if a number is a perfect square) but I can't find it out.

edit: replaced z^^2 with z*z

Prolog (SWI), 36 bytes

\N:-1+N+0.
Y+N+X:-X<N,X+Y+N+Y;X=:=N.

Try it online!

Bash, 87 bytes

read z;f=0;g=1;h=1
for((;;)){
h=$(($f+$g))
if [ $z == $f ];then echo 1;fi  
f=$g;g=$h
}

Attention endless loop, no break - stop the code after some seconds manually

Try it online!

brev, 46 bytes

(c(fn(or(= x z)(and(< x z)(f y(+ x y)z))))0 1)

Vyxal r, 4 bytes

ÞFce

Try it Online! - show all boolean results
Try it Online! - show only numbers returning truthy

Thanks to Steffan. This based on the alternative 5 byte answer below, removing the need for the $.

Vyxal, 5 bytes

ÞF0pc

Try it Online! - show all boolean results
Try it Online! - show only numbers returning truthy

ÞF   # All 1-indexed Fibonacci numbers as a LazyList.
0p   # Prepend the list with 0
c    # Is the input contained in the list?

Alternative 5 bytes:

ÞFc$e

Try it Online! - show all boolean results
Try it Online! - show only numbers returning truthy

ÞF   # All 1-indexed Fibonacci numbers as a LazyList.
c    # Is the input contained in the list?
$    # Swap above result with the input (this creates a copy of the input)
e    # Exponentiate. For an input of zero this will yield 0**0 == 1; for other
     # Fibonacci numbers, 1**{n>0} == 1; otherwise 0**{n>0} == 0.

The above two solutions work around the fact that there's no 0-indexed version of ÞF. Alternatively using ∆F requires a different workaround, but it can also be done in 5 bytes:

Þn∆Fc

Try it Online! - show all boolean results
Try it Online! - show only numbers returning truthy

Þn  # All integers in an infinite list (0, 1, -1, 2, -2, ...)
∆F  # nth Fibonacci number, 0-indexed
c   # Contains - Check if one thing contains another

Using ʀ (Inclusive range [0..input]) instead of Þn wouldn't work, because the Fibonacci numbers \$2\$ and \$3\$ are not members of the lists \$[0,1,1]\$ and \$[0,1,1,2]\$ respectively. It would be necessary to use ›ʀ (the range [0..input+1]), but for non-Fibonacci numbers that is exponentially slower than using Þn (and Þn∆Fc is in turn a bit slower than ÞFc$e).

Note that Þn includes negative numbers, and ∆F on a negative number returns a negative Fibonacci number. However, Þn∆Fc only returns truthy for nonnegative Fibonacci numbers, probably due to a bug in Vyxal.


Without using any Fibonacci builtins (7 bytes):

k≈⁽+dḞc

Try it Online! - show all boolean results
Try it Online! - show only numbers returning truthy

The is based on lyxal's answer to Fibonacci function or sequence.

k≈   # the list [0, 1]
⁽+d  # lambda x, y: x + y
Ḟ    # Create an infinite sequence based on the function and the initial list.
c    # Does the list contain the input?

dc, 34 bytes

d0r^+0 1[d3R+d4Rd_5R>s]dssx0r4R-^p

Try it online!

Prints 1 if the number at the top of the stack is a fibonacci number, 0 otherwise.

Regex (ECMAScript), 392 358 328 224 206 165 164 162 161 bytes

-1 byte by using ECMAScript non-participating capture group behavior
-2 bytes by by calculating \$F_{2n+3}\$ differently
-1 byte by moving around a remainder

The techniques that need to come into play to match Fibonacci numbers with an ECMAScript regex (in unary) are a far cry from how it's best done in most other regex flavors. The lack of forward/nested backreferences or recursion means that it is impossible to directly count or keep a running total of anything. The lack of lookbehind makes it often a challenge even to have enough space to work in.

Many problems must be approached from an entirely different perspective, and seem unsolvable until the arrival of some key insight. It forces you to cast a much wider net in finding which mathematical properties of the numbers you're working with might be able to be used to make a particular problem solvable.

In March 2014, this is what happened for Fibonacci numbers. Looking at the Wikipedia page, I initially couldn't figure out a way, though one particular property seemed tantalizingly close. Then the mathematician teukon outlined a method that made it quite clear it would be possible to do, using that property along with another one. He was reluctant to actually construct the regex. His reaction when I went ahead and did it:

You're crazy! ... I thought you might do this.

As with my other ECMAScript unary math regex posts, I'll give a warning: I highly recommend learning how to solve unary mathematical problems in ECMAScript regex. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. See that post for a list of consecutively spoiler-tagged recommended problems to solve one by one.

So do not read any further if you don't want some unary regex magic spoiled for you. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above.

The challenge I initially faced: A positive integer x is a Fibonacci number if and only if 5x2 + 4 and/or 5x2 - 4 is a perfect square. But there is no room to calculate this in a regex. The only space we have to work in is the number itself. We don't even have enough room to multiply by 5 or take the square, let alone both.

teukon's idea on how to solve it (originally posted here):

The regex is presented with a string of the form ^x*$, let z be its length. Check whether or not z is one of the first few Fibonacci numbers by hand (up to 21 should do). If it is not:

  1. Read a couple of numbers, a Use forward look-aheads to build a2, ab, and b2.
  2. Assert that either 5a2 + 4 or 5a2 - 4 is a perfect square (so a must be Fn-1 for some n).
  3. Assert that either 5b2 + 4 or 5b2 - 4 is a perfect square (so b must be Fn).
  4. Check that z = F2n+3 or z = F2n+4 by using the earlier built a2, ab, and b2, and the identities:
    • F2n-1 = Fn2 + Fn-12
    • F2n = (2Fn-1 + Fn)Fn

In brief: these identities allow us to reduce the problem of checking that a given number is Fibonacci to checking that a pair of much smaller numbers are Fibonacci. A little algebra will show that for large enough n (n = 3 should do), F2n+3 > Fn + 5Fn2 + 4 so there should always be enough space.

And here is a mockup of the algorithm in C which I wrote as a test before implementing it in regex. My final golfed regex is rather different. There turned out to be no need to find both \$a\$ and \$b\$, because \$b\$ is the Lucas number \$L_n\$, which along with \$F_n\$ can be used to derive \$F_{2n+2}\$ and \$F_{2n+3}\$ as needed:

So with no further ado, here is the regex:

^(?=(x*).*(?=x{4}(x{5}(\1{5}))(?=\2*$)\3+$)(|x{4})(?=xx(x*)\5)\4(x(x*))(?=(\6*)\7+$)(?=\6*$\8)\6*(?=x\1\7+$)(x*)(\9x?)|)(\9\10(\5\10)\12?|xx?x?|x{5}|x{8}|x{21})$

Try it online!

And the pretty-printed, commented version:

^                          # tail = N = input number
(?=
    (x*)                   # \1+1 = potential number for which 5*(\1+1)^2 ± 4 is a
                           # perfect square; this is true iff \1+1 is a Fibonacci number,
                           # which we shall call F_n. Outside the surrounding lookahead
                           # block, \1+1 is guaranteed to be the largest number for which
                           # this is true such that \1 + 5*(\1+1)^2 + 4 <= N.
    .*
    (?=                    # tail = (\1+1) * (\1+1) * 5 + 4
        x{4}
        (                  # \2 = (\1+1) * 5
            x{5}
            (\1{5})        # \3 = \1 * 5
        )
        (?=\2*$)
        \3+$
    )
    (|x{4})                # \4 = parity - determined by whether the index of Fibonacci
                           #               number \1+1 is odd or even;
    (?=
        xx                 # tail = arithmetic mean of (\1+1) * (\1+1) * 5 and \6 * \6
                           #      = ((F_n * F_n * 5) + (L_n * L_n)) / 2 = L_{2n}
        (x*)\5             # \5 = floor(tail / 2) = floor(L_{2n} / 2)
    )
    \4
    # require that the current tail is a perfect square
    (x(x*))                # \6 = potential square root, which will be the square root
                           #      after the following two lookaheads; \7 = \6-1
    (?=(\6*)\7+$)          # \8 = must be zero for \6 to be a valid square root
    (?=\6*$\8)
    # \6 is now the Lucas number L_n corresponding to the Fibonacci number F_n.
    \6*
    (?=x\1\7+$)            # tail = F_{2n} = L_n * F_n = \6 * (\1+1), where \6 is larger
    (x*)(\9x?)             # \9 = floor(tail / 2);
                           # \10 = ceil(tail / 2); the remainder tail % 2 will always be
                           #       the same as the remainder discarded by \5, because
                           #       F_{2n} is odd iff L_{2n} is odd, thus this ceil()
                           #       can complement the floor() of \5 when adding \5 + \10
|                          # Allow everything above to be skipped, resulting in all
                           # capture groups being unset.
)
(
    # Note that if the above was skipped using the empty alternative in the lookahead,
    # the following will evaluate to 0. This relies on ECMAScript NPCG behavior.
    \9\10(\5\10)           # \12  = F_{2n+1} = (L_{2n} + F_{2n})/2 = \5 + \10;
                           # head = F_{2n+2} = F_{2n}   + F_{2n+1}
                           #                 = \9+\10   +   \12
    \12?                   # head = F_{2n+3} = F_{2n+2} + F_{2n+1}    (optionally)
                           #                 = head     +   \12
|
    xx?x?|x{5}|x{8}|x{21}  # The Fibonacci numbers 1, 2, 3, 5, 8, 21 cannot be handled
                           # by our main algorithm, so match them here; note, as it so
                           # happens the main algorithm does match 13, so that doesn't
                           # need to be handled here.
)$

The multiplication algorithm is not explained in those comments, but is briefly explained in a paragraph of my abundant numbers regex post.

I was maintaining six different versions of the Fibonacci regex: four that ratchet from shortest length to fastest speed and use the algorithm explained above, and two others that use a different, much faster but much more lengthy algorithm, which as I found can actually return the Fibonacci index as a match (explaining that algorithm here is beyond the scope of this post, but it's explained in the original discussion Gist). I don't think I would maintain that many very-similar versions of a regex again, because at the time I was doing all my testing in PCRE and Perl, but my regex engine is fast enough that concerns of speed are not as important anymore (and if a particular construct is causing a bottleneck, I can add an optimization for it) – though I'd probably again maintain one fastest version and one shortest version, if the difference in speed were big enough.

The "return the Fibonacci index minus 1 as a match" version (not heavily golfed):

Try it online!

All of the versions are on github with the full commit history of golf optimizations:

regex for matching Fibonacci numbers - short, speed 0.txt (the shortest but slowest one, as in this post)
regex for matching Fibonacci numbers - short, speed 1.txt
regex for matching Fibonacci numbers - short, speed 2.txt
regex for matching Fibonacci numbers - short, speed 3.txt
regex for matching Fibonacci numbers - fastest.txt
regex for matching Fibonacci numbers - return index.txt

CSASM v2.1.2.3, 259 bytes

func main:
push 0
pop $1
push 1
pop $2
in ""
conv i32
pop $a
push $a
push 1
comp.lte
push $f.o
brfalse c
.lbl b
push 1
print
ret
.lbl a
push 0
print
ret
.lbl c
clf.o
push $1
dup
push $2
add
pop $1
pop $2
push $1
push $a
comp.gt
push $f.o
brtrue a    
push $1
push $a
comp
push $f.o
brtrue b
br c
ret
end

Commented and ungolfed:

func main:
    ; Seed the sequence ($1 = new value, $2 = old value)
    push 0
    pop $1
    push 1
    pop $2

    ; Get the input, convert it to an integer and store it in the accumulator
    in ""
    conv i32
    pop $a

    ; If $a <= 1, print truthy (1)
    push $a
    push 1
    comp.lte
    push $f.o
    brfalse loop

.lbl isFib
    ; Print a truthy value
    push 1
    print
    ret
.lbl notFib
    ; Print a falsy value
    push 0
    print
    ret

    ; Keep generating new Fibonacci numbers until $1 is >= $a
    .lbl loop
        ; Clear the Comparison flag
        clf.o
        
        ; Get the next Fibonacci pair:
        ; $2 = $1, $1 = $1 + $2
        push $1
        dup
        push $2
        add
        pop $1
        pop $2

        ; If $1 > $a, the input wasn't a Fibonacci number
        push $1
        push $a
        comp.gt
        push $f.o
        brtrue notFib
        
        ; If $1 == $a, the input was a Fibonacci number
        push $1
        push $a
        comp
        push $f.o
        brtrue isFib

        ; Still need to generate more numbers
        br loop
    ret
end

Java (JDK), 37 bytes

s->s.matches(".?|(\\2?+(\\1|^.))*..")

Try it online!

This works for numbers up to 1,836,311,903 (47th fibonacci number) included. Above that, the result is undefined (including a potential infinite loop).

Credits

k4, 30 26 bytes

-4 thanks to ngn!

{x in(x>*|:){x,+/-2#x}/!2}

the above is a simple while iterator. (cond){func}/arg.

            {x,+/-2#x}           / x join sum over last 2 elements of x (i.e. append next Fib)
     (x>*|:)          /!2        / while outer func input is greater than last element (x>*|:) of inner func output, pass inner func output to inner func
 x in                            / check if x is in array. returns boolean

Brachylog, 16 14 bytes

1;0⟨t≡+⟩ⁱhℕ↙.!

Try it online!

Takes input through the output variable and outputs through success or failure, and in the case of success the input variable is unified with 1.

1;0               Starting with [1,0],
        ⁱ         iterating
   ⟨ ≡ ⟩          replacing
   ⟨t  ⟩          the first element of the pair with the last element
   ⟨  +⟩          and the last element with the sum of the pair
         h        until the first element
          ℕ↙      is greater than or equal to
            .     the output variable,
             !    and stopping then,
         h        the first element of the pair is equal to the output variable.

ℕ↙.! is necessary for it to terminate on false test cases.

MathGolf, 4 bytes

⌠rf╧

Try it online!

Explanation

We need to increment the input twice before creating the range because we know that \$F_{n+1} \geq n,\forall n \geq 0\$.

⌠      increment twice
 r     range(0, n)
  f    pop a, push fibonacci(a) (maps to the range)
   ╧   pop a, b, a.contains(b) (check if input is in list)

ZX81 BASIC 180 151 100 ~94 tokenized BASIC bytes

With thanks to Moggy on the SinclairZXWorld forums, here is a much neater solution that saves more bytes.

 1 INPUT I
 2 FOR F=NOT PI TO VAL "1E9"
 3 LET R=INT (VAL ".5"+(((SQR VAL "5"+SGN PI)/VAL "2")**I)/SQR VAL "5")
 4 IF R>=I THEN PRINT F=R
 5 IF R<I THEN NEXT F

This will output 1 if a Fibonacci number is entered, or zero if not. Although this saves bytes, it's much slower than the old solutions below. For speed (but more BASIC bytes) remove the VAL wrappers around the string literal numbers. Here is the old(er) solutions with some explanations:

 1 INPUT A$
 2 LET A=SGN PI
 3 LET B=A
 4 LET F=VAL A$
 5 IF F>SGN PI THEN FOR I=NOT PI TO VAL "1E9"
 6 LET C=A+B
 7 LET A=B
 8 LET B=C
 9 IF B>=F THEN GOTO CODE "£"
10 IF F THEN NEXT I
12 PRINT STR$(SGN PI*(B=F OR F<=SGN PI)) AND F>=NOT PI;"0" AND F<NOT PI

The amendments above saves further BASIC bytes to condensing the IF statements into a single PRINT in line 12; other bytes were saved by using the VAL keyword and, and using GOTO CODE "£", which in the ZX81 character set is 12. Strings save more bytes over numbers as all numeric values are stored as floats so therefore take more space on the VAR stack.

enter image description here

cQuents, 8 bytes

=0,1?Z+Y

Try it online!

Explanation

=0,1        Set sequence start to 0,1
    ?       Mode: Query (assumes increasing sequences)
     Z+Y    Each item is the previous two summed

Alchemist, 205 134 bytes

Big thanks to ASCII-only for rather clever merging of states, saving 71 bytes!!

_->In_x+c+u
u+b->u+a+d
u+0b->v
v+c->v+b+d
v+0c->w
w+a+x->w+y
w+0a+0x->Out_"1"
w+a+0x->Out_"0"
w+0a+x+y->w+2x
w+0a+0y+d->w+c
w+0d+0a->u

Try it online or verify in batch!

Ungolfed

# read input, initialize (c = 1)
_ -> In_x + c + s0

# a,d <- b
s0 +  b -> s0 + a + d
s0 + 0b -> s1

# b,d <- c
s1 +  c -> s1 + b + d
s1 + 0c -> s2

s2 +  a +  x -> s2 + y            # y <- min(a,x)
s2 + 0a + 0x -> Out_"1"           # if (a == x): was Fibonacci
s2 +  a + 0x -> Out_"0"           # if (a >  x): stop (we exceeded target)
s2 + 0a +  x +  y -> s2 + 2x      # if (a <  x): x += a (since y = a) / restore x
s2 + 0a      + 0y +  d -> s2 + c  # once that's done; c <- d
s2 + 0a           + 0d->s0        # and finally loop

Ruby, 64 41 40 bytes

->n,a=b=1{a,b=b,a+b;a<n ?redo:a>n ?p: 1}

Try it online!

C# (.NET Core), 51 bytes

bool f(int n,int a=0,int b=1)=>a<n?f(n,b,a+b):a==n;

Try it online!

-6 bytes thanks to @Oliver!

This solution uses a pretty straightforward recursive function.

The TIO link demonstrates this working for 1134903170 which exceeds the maximum value required by the challenge.

><>, 21 19+3 = 24 22 bytes

i1\{=n;
?!\:@+:{:}(

Input is expected to be on the stack at program start, so +3 bytes for the -v flag.

Try it online!

This works by generating Fibonacci numbers until they are greater than or equal to the input number, then checking the last generated number for equality with the input. Outputs 1 if it was a Fibonacci number, 0 otherwise.

To ensure that 0 is handled correctly, the seed is -1 1 - the first number generated will be 0 rather than 1.

Thanks to @cole for pointing out that i can be used to push -1 onto the stack when STDIN is empty. Very clever!

Previous version:

01-1\{=n;
}(?!\:@+:{:

[Python 3], 48 bytes

m=0;k=1;exec("k,m=m,m+k\nif k==n:print(1)\n"*n)

If n is the input, we generate the first n Fibonacci numbers and check if our input is one of them.

C, 36 bytes

f(x,a,b){return x>b?f(x,b,a+b):x==b}

It puts some warnings, and requires at least 32-bit integers. Newer C standards probably won't even compile it. It should be called as f(142857,0,1).

Bonus: it can calculate Fibonacci-ness with different initial values, too.

Neim, 2 bytes

f𝕚

Explanation:

f       Push an infinite fibonacci list
 𝕚      Is the input in that list?

Works the same as my It's Hip to be Square answer, but uses a different infinite list: f, for fibonacci.

Try it!

Japt, 8 7 bytes

ÆMgXÃøU

Test it


Explanation

Implicit input of integer U.

Æ   Ã

Generate an array of integers from 0 to U-1 and pass each through a function where X is the current element.

MgX

Get the Xth Fibonacci number.

øU

Check if the array contains (ø) the original input U. Implicitly return the boolean result.

Common Lisp, 61 54 bytes

(defun f(x)(do((a 0 b)(b 1(+ a b)))((>= a x)(= a x))))

Try it online!

The reduction in size with respect to the previous version:

(defun f(x)(do((a 0 b)(b 1 c)(c 1(+ b c)))((>= a x)(= a x))))

was triggered by the idea that to generate the sequence of the Fibonacci numbers only two variables are necessary, not three.

Python 3, 59 Bytes

f=5*int(input())**2
print(not((f+4)**0.5%1and(f-4)**0.5%1))

Python 3, 56 53 50 bytes

def f(m):
 a=b=1
 while a<m:b,a=a,a+b
 print(a==m)

Try it online!

R, 32 31 bytes

Takes input from stdin, returns TRUE or FALSE as appropriate.

any(!(5*scan()^2+-1:1*4)^.5%%1)

><>, 33+3 = 36 bytes

3 bytes added for the -v flag

10:{:}=?!v1n;
)?v:@+10.\:{:}
n0/;

Try it online!

Or 54 bytes without using the -v flag

 0ic4*-:0(?v$a*+10.
:{:}=?!v1n;\10
v:@+d1.\:{:})?
\0n;

Try it online!

D, 57 bytes

A nice, clean, no-nonsense solution:

int f(int n,int x=0,int y=1){return y<n?f(n,y,x+y):y==n;}

This one is 58 bytes but doesn't use recursion, and so might be more practical for larger inputs:

alias f=(n){int x,y=1;for(;y<n;y+=x,x=y-x){}return y==n;};

And here's one where the function declaration itself is only 54 bytes, though it depends on the mach library.

import mach.range : r=recur, l=last;
import mach.math.vector : v=vector;
const z=v(0,1);

// The 54-byte function
alias f=n=>z.r!(a=>v(a.y,a.x+a.y),a=>a.y>n).l(z).y==n;

// Exploded for readability
alias f=n=>(
    vector(0,1) // Seed the sequence
        .recur!(v=>vector(v.y,v.x+v.y),v=>v.y>n) // Compute Fib numbers until N
        .last(vector(0,1)).y == n // If the last number was N, return true
        // Value in parens "last(...)" is a fallback for n==0 and empty seq.
);

Java, 40 bytes

r->Math.abs((r*Math.sqrt(5)-~r)%2*r-r)<2

This is a straight Java port of @xnor's answer.

Cubix, 22 24 bytes

0 is truthy, nothing is falsey

@0O1I!^/@.W<rq\?-p+;;u

Try it online!

    @ 0
    O 1
I ! ^ / @ . W <
r q \ ? - p + ;
    ; u
    . .

Watch it run

I may be able to get a couple more out of this ... found them with a change to the initial redirect into the loop

Actually, 2 bytes

fu

Try it online!

Pushes either a positive number for truthy or 0 for falsy.

AWK, 56 63 61 bytes

{for(n[++j]++;n[j]<$1;n[++j]=n[j]+n[j-1]){}$0=$0?n[j]==$1:1}1

Try it online!

Brute force is fun. :) If you want it to work for arbitrarily large numbers, add a -M argument, but that is outside the scope of the problem.

7 bytes added to account for 0 as input, but shaved a couple off using the ternary operator.

Julia 0.4, 29 bytes

!m=in(0,sqrt(5*m*m+[4,-4])%1)

Try it online!


If this isn't how you do a Julia answer, let me know. I'm unsure of how input works on TIO.

Javascript (ES6 without the ** operator), 44 bytes

f=(x,c=x*(Math.sqrt(5)-1)/2%1)=>x*(c-c*c)<.5

Relies on the ratio between successive Fibonacci numbers approaching the golden ratio. The value of c is the fractional part of the input divided by the golden ratio - if the input is Fibonacci then this will be very close to 1 and the value of c-c² will be very small.

Not as short as some of the other JS answers but runs in O(1) time.

><>, 40 83 bytes

Added 43 bytes so that it takes the correct input

i:0(?vc4*-
 v&a~<
+>l2(?v$&:a*&*
v   ~&<
>10r:&1)?v1n;
=?v&:&)?v>:{+::&:&
  >1n;n0<

A less golfy version would be:

// Read input
i:0(?vc4*-
     >~a&v
         >l2(?v$&:a*&*+
              >&~04.
// Determine if in Fibonacci
 10r:&1)?v1n;
         >:{+::&:&=?v&:&)?v
                    >1n;n0<

Swift, 72 bytes

func f(i:Int,a:Int=0,b:Int=1)->Bool{return a<i ?f(i:i,a:b,b:a+b) :i==a}

Un-golfed:

func f(i:Int, a:Int=0, b:Int=1)->Bool{
    return a<i ? f(i: i, a: b, b: a+b) : i==a
}

I am recursively calling f until a is equal to or greater then i. Then, I check to see if i and a are equal.

You can try it here

PHP, 44 bytes

for(;0>$s=$x-$argn;)$x=+$y+$y=$x?:1;echo!$s;

Try it online!

PHP, 58 bytes

for($x=0,$y=1;$x<$argn;$x=$y,$y=$t)$t=$x+$y;echo$x==$argn;

Try it online!

05AB1E, 8 7 bytes

>ÅF¹å¹m

Explanation:

>ÅF       # Generate Fibbonacci numbers up to n+1
   ¹å     # 0 if original isn't in the list, 1 if it is
     ¹m   # 0**0 = 1 if input was 0 (hotfix for 0).
          # or 0**n if not fibb / 1**n if it is a fibb.

Try it online!

-1 thanks to Jonathan Allan for the 0-not-a-fibonacci-number workaround.

05AB1E, 7 bytes

ÅF夹_~

Try it online!

Java 8, 94 bytes

x->{int i=0;for(;c(i++)<=x;);return c(i-2)==x;}int c(int n){return n<1?0:n<2?1:c(n-1)+c(n-2);}

Explanation:

Try it here. (NOTE: It's a bit slow for very large test-cases.)

x->{                 // Method (1) with integer parameter and boolean return-type
  int i=0;           //  Index
  for(;c(i++)<=x;);  //  Loop as long as the Fibonacci number is smaller or equal to the input
  return c(i-2)==x;  //  And then return if the input equals the previous Fibonacci number
}                    // End of method (1)

                     // Method to get `n`th Fibonacci number
int c(int n){        // Method (2) with integer parameter and integer return-type
  return n<1?        //  If `n`==0:
    0                //   Return 0
   :n<2?             //  Else if `n`==1
    1                //   Return 1
   :                 //  Else:
    c(n-1)+c(n-2);   //   Return recursive calls with `n-1` and `n-2`
}                    // End of method (2)

Haskell, 31 bytes

f=0:scanl(+)1f
(`elem`take 45f)

Try it online! This exploits the fact that the input will be in the range from 0 to 1,000,000,000, hence we need to check only the first 45 Fibonacci numbers. f=0:scanl(+)1f generates an infinite list of Fibonacci numbers, take 45f is the list of the first 45 Fibonacci numbers and elem checks whether the input is in this list.


Unrestricted version: 36 bytes

f=0:scanl(+)1f
g n=n`elem`take(n+3)f

Try it online! For any n, taking the first n+3 Fibonacci numbers will guarantee that n will be in this list if it's a Fibonacci number.

Note that this approach is incredible inefficient for high numbers that are not Fibonacci numbers, because all n+3 Fibonacci numbers need to be computed.

QBIC, 24 bytes

≈g<:|g=p+q┘p=q┘q=g]?g=a

Explanation

≈g<:|   WHILE g (running fibonacci total) is less than input
g=p+q   Get the next fib by adding p (n-2, starts as 0) and q (n-1, starts as 1)
┘       (Syntactic linebreak)
p=q     increase n-2
┘       (Syntactic linebreak)
q=g     increase n-1
]       WEND
?g=a    PRINT -1 if g equals input (is a fib-number), or 0 if not.

Mathematica, 30 bytes

Or@@EvenQ[2Sqrt[5#^2+{4,-4}]]&

Pari/GP, 32 bytes

n->!prod(x=0,n+1,fibonacci(x)-n)

Try it online!

MATL (16 bytes)

2^5*4-t8+hX^tk=s

Try it online!

Not the golfiest solution, but wanted to use the direct method of checking if "5*x^2+/-4" is a perfect square.

Explanation:

2^5*    % 5 times the input squared
4-      % push the above minus 4
t8+     % push the above plus 8 (+4 overall)
hX^     % concatenate them into an array and then take the sqrt().
tk      % push a copy of the array that is rounded using floor().
=       % test if the sqrt's were already integers
s       % sum the results, returns 0 if neither was a perfect square.

Note:

In the "0" case it returns "2" because both 4 and -4 are perfect squares, same with 1 which produces "1 1". Consider any non-zero output as "truthy", and 0 as "falsy".

k, 20 bytes

{*x=*|(*x>)(|+\)\1 1}

Generates fibonacci numbers until it overshoots. Then it checks the last one it generated for equality. 1 is truthy, 0 is falsey.

Try it online.

Python 2, 48 44 bytes

f=lambda n,a=0,b=1:n>a and f(n,b,a+b)or n==a

Try it online

Thanks to Jonathan Allan for saving 4 bytes

Javascript, 89 bytes

function f(n){s=Math.sqrt;c=Math.ceil;x=5*n**2;a=s(x-4);b=s(x+4);return c(a)==a||c(b)==b}

This uses the fact that all fibonacci numbers have the property that 5x^2+4 or 5x^2-4 must be square. It takes the square root of these numbers and checks if they equal their ceiling value.

Javascript, 69 bytes (if it doesn't need to be a function)

s=Math.sqrt;c=Math.ceil;x=5*n**2;a=s(x-4);b=s(x+4);n=c(a)==a||c(b)==b

This one does the exact same thing, except instead of calling a function, you set n to the number to test, and n is set to true/false based on the result.

This is my first code golf entry, so let me know if there's anything to improve here. :)

Clojure, 61 bytes

(def s(lazy-cat[0 1](map +(rest s)s)))#((set(take(inc %)s))%)

This actually constructs the Fibonacci sequence s, grabs enough elements from it and checks if the input is found. Returns nil for falsy and the input number for truthy.

CJam, 37 bytes

ri1T{\1$+_3$-g"1T 0_ 1"S/=~}g]W=

CJam has no Fibonnaci built-in. On the bright side, this does use g twice, and I think this is the first time I've ever used it!

C (gcc), 50 bytes

a,b,c;f(n){for(a=0,b=1;n>(c=a);b=c)a+=b;n=(n==c);}

Try it online!

R, 43 40 bytes

pryr::f(x%in%DescTools::Fibonacci(0:45))  

pryr::f creates a function:

function (x) 
x %in% DescTools::Fibonacci(0:45)

Uses DescTools::Fibonacci to create the first x+1 fibonacci numbers and checks for inclusion. x+1 because the third fibnum is 2, and that wouldn't be enough to check for inclusion of 3.

Luckily Desctools::Fibonacci(0)=0, so that is a nice freebee.

-3 bytes thanks to MickyT

Dyalog APL, 17 bytes

0∊1|.5*⍨4 ¯4+5××⍨

Try it online!

C#, 109 bytes

bool f(int n){int[]i=new[]{0,1,0};while(i[0]<n||i[1]<n){i[i[2]%2]=i[0]+i[1];i[2]++;}return n==i[0]||n==i[1];}

Definitely could be improved, but I didn't have time.

Jelly,  8 7  6 bytes

-r‘ÆḞċ

Try it online!

How?

-r‘ÆḞċ - Link: non negative number, n
-      - literal -1      = -1
 r     - inclusive range = [-1,0,1,2,3,4,5,...,n]
  ‘    - increment n     = [ 0,1,2,3,4,5,6,...,n+1]
   ÆḞ  - Fibonacci       = [ 0,1,1,2,3,5,8,...,fib(n+1)]
     ċ - count occurrences of n (1 if n is a Fibonacci number, 0 otherwise)

Notes:

Mathematica, 37 bytes

!Fibonacci@n~Table~{n,0,#+1}~FreeQ~#&

-4 bytes from @ngenisis

Retina, 23 bytes

^$|^(^1|(?>\2?)(\1))*1$

Try it online!

Input in unary, outputs 0 or 1.

Explanation

The Fibonacci sequence is a good candidate for a solution with forward references, i.e. a "backreference" that refers either to a surrounding group or one that appears later in the regex (in this case, we're actually using both of those). When matching numbers like this, we need to figure out a recursive expression for the difference between sequence elements. E.g. to match triangular numbers, we usually match the previous segment plus one. To match square numbers (whose differences are the odd numbers), we match the previous segment plus two.

Since we obtain the Fibonacci numbers by adding the second-to-last element to the last one, the differences between them are also just the Fibonacci numbers. So we need to match each segment as the sum of the previous two. The core of the regex is this:

(         # This is group 1 which is repeated 0 or more times. On each
          # iteration it matches one Fibonacci number.
  ^1      # On the first iteration, we simply match 1 as the base case.
|         # Afterwards, the ^ can no longer match so the second alternative
          # is used.
  (?>\2?) # If possible, match group 2. This ends up being the Fibonacci
          # number before the last. The reason we need to make this optional
          # is that this group isn't defined yet on the second iteration.
          # The reason we wrap it in an atomic group is to prevent backtracking:
          # if group 2 exists, we *have* to include it in the match, otherwise
          # we would allow smaller increments.
  (\1)    # Finally, match the previous Fibonacci number and store it in
          # group 2 so that it becomes the second-to-last Fibonacci number
          # in the next iteration.
)*

Now this ends up adding the Fibonacci numbers starting at 1, i.e. 1, 1, 2, 3, 5, .... Those add up to 1, 2, 4, 7, 12, .... I.e. they are one less than the Fibonacci numbers, so we add a 1 at the end. The only case this doesn't cover is zero, so we have the ^$ alternative at the beginning to cover that.

Groovy, 44 43 37 bytes

{n->[-4,4].any{!((n*n*5+it)**0.5%1)}}

If (5*(n**2)±4)**0.5 is ever an integer, the number is a fibbonacci number.

JS (ES6), 78 bytes

n=>{y=n?0:1;f=x=>x<3?1:f(x-1)+f(x-2);for(x=0;x<n+2;x++)f(x)==n?y=1:0;return y}

Ungolfed:

var f = n => {
    var y = n ? 0 : 1;
    f=x=>x<3?1:f(x-1)+f(x-2);//from this: https://codegolf.stackexchange.com/a/25142/70700
    for (var x = 0; x < n + 2; x++){
        if(f(x) == n){
            y = 1;
        }else{
            y = 0;
        }
    }
    return y;
};

JS (ES6), 57 bytes

n=>(y=y=>((5*(n**2)+y)**0.5),~~y(4)==y(4)|~~y(-4)==y(-4))

Uses carusocomputing's method. Alot golfier than my other answer.

Ungolfed

n=>{
    y=y=>((5*(n**2)+y)**0.5);//carusocomputing's method in a function
    return ~~y(4) === y(4) || ~~y(-4) === y(-4);//~~x === Math.floor(x)
}

Mathematica, 33 bytes

AtomQ@*InverseFunction[Fibonacci]

Jelly, 5 bytes

ȷḶÆḞi

Try it online!

Returns 0 for non-Fibonacci numbers, and the 1-indexed position of the number in the Fibonacci sequence for Fibonacci numbers.

Explanation:

ȷḶÆḞi
ȷ        The literal number 1000
 Ḷ       Range [0,1,...,999]
  ÆḞ     Get the ith Fib number; vectorizes [1,1,2,3,5,...,<1000th Fib number>]
    i    Get the first index of element in list, or 0 if not found

Swift, 66 bytes

func f(n:Int){var a=0,b=1,c=0;while n>a{c=a;a=b;b=c+b};print(n<a)}

Try it out! - NOTE: Prints False as truthy and True for falsy.

Seriously, 3 bytes

,fu

Try it online!

Returns the index +1 in the list of Fibonacci numbers if truthy, otherwise returns falsy.

Explanation:

,fu
,   read input
 f  0-indexed index of that number in the fibonacci sequence (-1 if not in the sequence)
  u increment. (Makes the -1 value falsy and the 0-value truthy)

JavaScript (ES6), 34 bytes

f=(n,x=0,y=1)=>x<n?f(n,y,x+y):x==n

Recursively generates the Fibonacci sequence until it finds an item greater than or equal to the input, then returns item == input.

Python 3, 48 bytes

lambda n:0in((5*n*n+4)**.5%1,abs(5*n*n-4)**.5%1)

Try it online!

Perl 6, 23 bytes

{$_∈(0,1,*+*...*>$_)}