Introduction
We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n
your job is to find n
.
Specification
Input
Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.
Output
The output must be a non-negative integer as well.
What to do?
The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2)
and you're given F(n)
and must return n
.
Potential Corner Cases
0 is a valid in- and output.
If given "1" as input you may either output "1" or "2", as you prefer.
You may always assume that your input actually is a fibonacci number.
You may assume that the input is representable as a 32-bit signed integer.
Who wins?
This is code-golf so the shortest answer in bytes wins!
Standard rules apply of course.
Test-cases
0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
50 Answers 50
Actually, 1 byte
f
Yes, there's a builtin for this, since November 16, 2015.
For fun, without the builtin, it's 9 bytes:
╗1`F╜=`╓i
Explanation:
╗1`F╜=`╓i
╗ push input to register 0
1`F╜=`╓ push list containing first value x (starting with x = 0) where:
F fib(x)
╜= is equal to the input
i flatten the list
-
21\$\begingroup\$ I have one thought and one thought only when I see this: ಠ_ಠ \$\endgroup\$Addison Crump– Addison Crump2016年07月17日 19:51:38 +00:00Commented Jul 17, 2016 at 19:51
-
41\$\begingroup\$ I don't really understand why you would "waste" a symbol for such a ridiculously specific purpose \$\endgroup\$Fatalize– Fatalize2016年07月17日 19:54:15 +00:00Commented Jul 17, 2016 at 19:54
-
22\$\begingroup\$ @Fatalize The Fibonacci and inverse Fibonacci functions were among the first that I added. Even now, there are 39 completely unused single-byte commands (and who knows how many overloads that could be utilized). The 256 symbols, combined with the fact that there are 5 types in Actually (Integer, Real, String, Iterable, Function), means there are up to 1280 possible unary functions, and 6400 possible binary functions. There's a lot of room for seemingly-useless commands. \$\endgroup\$user45941– user459412016年07月17日 19:56:24 +00:00Commented Jul 17, 2016 at 19:56
-
25\$\begingroup\$ @Mego Are you just trying to compete with Mathematica for the most builtins? \$\endgroup\$gcampbell– gcampbell2016年07月18日 10:07:17 +00:00Commented Jul 18, 2016 at 10:07
-
15\$\begingroup\$ Actually, it's just a byte... lol, love this language name. \$\endgroup\$nicael– nicael2016年07月18日 20:45:22 +00:00Commented Jul 18, 2016 at 20:45
Mathematica, 25 bytes
InverseFunction@Fibonacci
Function. Pretty self-explanatory if you ask me.
Python, (削除) 36 (削除ここまで) (削除) 34 (削除ここまで) 32 bytes
lambda n:len(str(66*n**6))//1.24
Previous versions:
f=lambda n:len(str(66*n**6))//1.24
f=lambda n:(n*n*7).bit_length()//1.4
Explanation
The core idea is to invert the formula
fibonacci(n) ~ ( (1 + sqrt(5)) / 2)**n / sqrt(5)
which tells us that
log fibonacci(n) ~ n log((1 + sqrt(5)) / 2) - log(sqrt(5))
to get
f(n) ~ (log(n) + log(sqrt(5))) / log((1 + sqrt(5))/2)
The golfing optimizations are:
- Use
len(str(n))
to compute log base 10 without importinglog
(old version used.bit_length()
to compute log base 2) - Raise
n
to a power, so that the approximation of the logarithm can distinguish between successive Fibonacci numbers - Multiplying by a constant scales up the values to get them in the correct range
Then the divisor was truncated to as little precision as I could manage and the multiplier chosen to give the correct results for all 32-bit fibonacci numbers.
-
\$\begingroup\$ it should be 32 bytes, because
f=
is not counted. \$\endgroup\$Leaky Nun– Leaky Nun2016年07月18日 06:07:43 +00:00Commented Jul 18, 2016 at 6:07 -
3\$\begingroup\$ As the comment above already said, anonymous functions/unnamed lambdas are allowed by default. Also, if you restrict your answer to Python 2 and require a long argument,
lambda n:~-len(`66*n**6`)//1.24
should work. \$\endgroup\$Dennis– Dennis2016年07月18日 06:46:19 +00:00Commented Jul 18, 2016 at 6:46
05AB1E, 3 bytes
Code:
ÅFg
Explanation:
ÅF # Generate all Fibonacci numbers <= input.
g # Get the length of this list.
Uses the CP-1252 encoding. Try it online!.
Julia, (削除) 27 (削除ここまで) (削除) 26 (削除ここまで) 18 bytes
!n=log(3n+.7)÷.48
This uses the inverse of Binet's formula, with just enough precision for 32-bit integers; it actually works up to F(153) = 42,230,279,526,998,466,217,810,220,532,898> 2105.
How it works
Binet's formula states the following.
Binet's formula
Restricting F to the set of Fibonacci, the map n → Fn has a right inverse F → nF.
We have that
right inverse of Binet's formula
and all that is left to do is dealing with the edge case 0.
Since the input is restricted to 32-bit integers, we can use short decimal literals instead of the constants in the formula.
log φ = 0.481211825059603447… ≈ 0.48
Unfortunately, 0.5 isn't precise enough.
√5 = 2.2360679774997896964… ≈ 3
That might seem like an awful approximation at first glance, but we're taking logarithms and since log 3 - log √5 = 0.29389333245105…, the result before rounding will be off by a small constant factor.
0.5 ≈ 0.7
Because of the excess from the previous approximation, we could actually omit this term altogether and still get correct results for F> 0. However, if F = 0, the logarithm will be undefined. 0.7 turned out to be the shortest value that extends our formula to F = 0.
Jelly, (削除) 14 (削除ここまで) 11 bytes
×ばつlØp+.Ḟ»0
This is my first ever Jelly answer! This uses the algorithm from the MATL answer. Thanks to Dennis for shaving off 3 bytes!
Explanation:
lØp # Log Base phi
51⁄2 # Of the square root of 5
×ばつ # Times the input
+ # Plus
. # 0.5
Ḟ # Floored
This gets the right answer, now we just need to handle the special case of '0'. With '0' as an arg, we get -infinity
, so we return
» # The maximum of
0 # Zero
# And the previous calculated value.
-
8\$\begingroup\$ +1 because the comments on the explanation are the end of a limerick. \$\endgroup\$Daniel– Daniel2016年07月18日 21:05:42 +00:00Commented Jul 18, 2016 at 21:05
JavaScript, (削除) 54 (削除ここまで) (削除) 50 (削除ここまで) (削除) 69 (削除ここまで) (削除) 50 (削除ここまで) 42 bytes
b=>(j=>{for(i=c=0;b-i;c++)i=j+(j=i)})(1)|c
Surely it isn't going to win, just for fun :)
(削除) Ok, checking for zero consumes 19 bytes. WTF? (削除ここまで) Stupid-me.
Demo! To see the last test case, you have to scroll the console a bit.
a=b=>(j=>{for(i=c=0;b-i;c++)i=j+(j=i)})(1)|c;
console.log('0: '+a(0));
console.log('2: '+a(2));
console.log('3: '+a(3));
console.log('5: '+a(5));
console.log('8: '+a(8));
console.log('13: '+a(13));
console.log('1836311903: '+a(1836311903));
Thanks @edc for shortening by 8 bytes.
-
\$\begingroup\$ simple
b=>{for(j=1,i=c=0;b-i;c++)i=j+(j=i);return c}
45, golfedb=>(j=>{for(i=c=0;b-i;c++)i=j+(j=i)})(1)|c
42. \$\endgroup\$edc65– edc652016年07月17日 20:51:39 +00:00Commented Jul 17, 2016 at 20:51
Perl 6 (削除) 33 30 (削除ここまで) 27 bytes
(削除) {first *==$_,:k,(0,1,*+*...*>$_)}
{first *==$_,:k,(0,1,*+*...*)} (削除ここまで)
{first $_,:k,(0,1,*+*...*)}
Explanation:
# lambda with implicit 「$_」 parameter
{
first # find the first element
$_, # where something is equal to the block's argument
:k, # return the key rather than the value
# of the Fibonacci sequence
( 0, 1, * + * ... * )
# ^--^ first two values
# ^---^ lambda used to generate the next in the series
# ^-^ generate until
# ^ Whatever
}
Test:
#! /usr/bin/env perl6
use v6.c;
use Test;
# using the safer version that stops generating
# values bigger than the input
my &fib-index = {first $_,:k,(0,1,*+*...*>$_)}
my @tests = (
0 => 0,
2 => 3,
3 => 4,
5 => 5,
8 => 6,
13 => 7,
1836311903 => 46,
1836311904 => Nil, # this is why the safe version is used here
12200160415121876738 => 93,
19740274219868223167 => 94,
354224848179261915075 => 100,
);
plan +@tests + 1;
for @tests -> $_ ( :key($input), :value($expected) ) {
cmp-ok fib-index($input), &[eqv], $expected, .gist
}
cmp-ok fib-index((0,1,*+*...*)[1000]), &[eqv], 1000, 'works up to 1000th element of Fibonacci sequence'
1..13
ok 1 - 0 => 0
ok 2 - 2 => 3
ok 3 - 3 => 4
ok 4 - 5 => 5
ok 5 - 8 => 6
ok 6 - 13 => 7
ok 7 - 1836311903 => 46
ok 8 - 1836311904 => Nil
ok 9 - 12200160415121876738 => 93
ok 10 - 19740274219868223167 => 94
ok 11 - 354224848179261915075 => 100
ok 12 - works up to 1000th element of Fibonacci sequence
-
1\$\begingroup\$ You can replace
first *==$_
with justfirst $_
, because a number is a valid smart-matcher. \$\endgroup\$smls– smls2017年02月27日 18:43:54 +00:00Commented Feb 27, 2017 at 18:43 -
Jelly, 8 bytes
1+С0
¢i
Try it online! Note that this approach is too inefficient for the last test case.
How it works
¢i Main link. Argument: n
¢ Call the helper link niladically (i.e., without arguments).
This yields the sequence of the first n positive Fibonacci numbers, i.e.,
[1, 1, 2, 3, 5, ...].
i Find the first index of n (1-based, 0 if not found).
1+С0 Helper link. No arguments.
1 Set the left argument to 1.
0 Yield 0.
+С Add both arguments, replacing the left argument with the sum and the right
argument with the previous value of the left argument.
Yield the array of all intermediate values of the left argument.
Python, 29 bytes
g=lambda n:n>.7and-~g(n/1.61)
Recursively divides the input by the golden-ratio approximation 1.61 until it's below 0.7, and outputs the number of divisions.
For 0, the code outputs False
, which equals 0 in Python. This can be avoided for 2 bytes
g=lambda n:n//.7and 1+g(n/1.61)
JavaScript, 22 bytes
n=>Math.log(n)/.48+2|0
-
\$\begingroup\$ I didn't think this would work when I saw it, but apparently
-Infinity|0
is0
in JavaScript. Go figure. \$\endgroup\$Dennis– Dennis2016年07月20日 16:43:16 +00:00Commented Jul 20, 2016 at 16:43 -
\$\begingroup\$ @Dennis: In JS, bitwise operators take only last 32 bits and
-Infinity = FFF00000 00000000
. I was glad to find out, it spares 3 bytes for not having to prepend an explicit zero test liken&&
. Apart from that, the main purpose of|0
is a substitute forMath.trunc()
(like÷
in Julia). \$\endgroup\$charlie– charlie2016年07月21日 12:38:58 +00:00Commented Jul 21, 2016 at 12:38
JavaScript (ES6), (削除) 39 (削除ここまで) 33 bytes
f=(n,j=0,k=1)=>n>j?f(n,k,j+k)+1:0
Even with ES7, the inverse Binet formula takes 47 bytes:
x=>Math.log(x*5**.5)/Math.log(.5+1.25**.5)+.5|0
x=>Math.log(x*5**.5)/Math.log((1+5**.5)/2)+.5|0
x=>Math.log(x*(p=5**.5))/Math.log((1+p)/2)+.5|0
-
\$\begingroup\$ Just distribute the
log
and precompute all constants... \$\endgroup\$charlie– charlie2016年07月19日 17:33:00 +00:00Commented Jul 19, 2016 at 17:33 -
\$\begingroup\$ IMHO, if you call recursively the lambda by name,
f(n,k,j+k)
, you should include the assignmentf=
and count it as +2 bytes. The rule for unnamed lambdas should not apply here. \$\endgroup\$charlie– charlie2016年07月21日 12:48:42 +00:00Commented Jul 21, 2016 at 12:48 -
\$\begingroup\$ @charlie Sorry, I always forgot about that. Fixed. \$\endgroup\$Neil– Neil2016年07月21日 13:27:38 +00:00Commented Jul 21, 2016 at 13:27
Sage, 49 bytes
lambda x,s=sqrt(5):x and int(log(x*s,(1+s)/2)+.5)
Thanks to TuukkaX for the suggestion about saving sqrt(5)
as s
to shave off a few bytes.
This approach using an inverse of Binet's formula offers several improvements over the previous approach: it's faster (constant-time versus quadratic time), it actually works for larger inputs, and it's shorter!
Python users may wonder why I'm using sqrt(5)
instead of the shorter 5**.5
- it's because 5**.5
is computed with C's pow
function, and loses precision due to floating point issues. Many mathematical functions (including sqrt
and log
) are overloaded in Sage to return an exact, symbolic value, which don't lose precision.
-
\$\begingroup\$ I don't know Sage at all but could you save bytes by holding the
sqrt(5)
in a variable and use it twice, instead of typingsqrt(5)
twice? \$\endgroup\$Yytsi– Yytsi2016年07月18日 11:27:13 +00:00Commented Jul 18, 2016 at 11:27
MATL, 14 bytes
t?5X^*17L&YlYo
This uses an inverse of Binet's formula, and so it's very fast.
Let F denote the n-th Fibonacci number, and φ the golden ratio. Then
The code uses this formula with two modifications:
- Instead of adding 1/2 and then rounding down, the code simply rounds towards the nearest integer, which takes up fewer bytes.
- Input F=0 needs to be treated as a special case.
How it's done
t % Take input F implicitly. Make a copy
? % If (copy of) F is positive
5X^ % Push sqrt(5)
* % Multiply by F
17L % Push phi (predefined literal)
&Yl % Two-input logarithm: first input is argument, second is base
Yo % Round towards nearest integer
% Else the input, which is 0, is left on the stack
% End if implicitly
% Display implicitly
-
1\$\begingroup\$ Alternate approach:
O1G:"yy+]vGmfq
\$\endgroup\$DJMcMayhem– DJMcMayhem2016年07月18日 22:06:06 +00:00Commented Jul 18, 2016 at 22:06 -
1\$\begingroup\$ 11 bytes:
t?17L&YlXkQ
\$\endgroup\$jimmy23013– jimmy230132019年08月31日 08:47:18 +00:00Commented Aug 31, 2019 at 8:47 -
\$\begingroup\$ @jimmy23013 Nice approach! You should definiely post that as a separate answer \$\endgroup\$Luis Mendo– Luis Mendo2019年08月31日 10:42:37 +00:00Commented Aug 31, 2019 at 10:42
-
\$\begingroup\$ I don't think it is worth another answer, as it is just a way to remove the
5X^*
. (I have done this before.) And I don't know MATL enough to possibly keep improving it. \$\endgroup\$jimmy23013– jimmy230132019年08月31日 17:12:01 +00:00Commented Aug 31, 2019 at 17:12
Prolog (SWI), 90 bytes
Written in conversation with flawr in chat.
F-N-A-B:-F=A;N>0,M is N-1,C is A+B,F-M-B-C.
F/N/I:-N=I,F-N-0-1;J is I+1,F/N/J.
F/N:-F/N/0.
Ungolfed
Here's a less-golfed version:
fib(F,0,F,_).
fib(F,N,A,B) :- N>0, M is N-1, C is A+B, fib(F,M,B,C).
fibindex(F,N,N) :- fib(F,N,0,1).
fibindex(F,N,I) :- J is I+1, fibindex(F,N,J).
fibindex(F,N) :- fibindex(F,N,0).
The fib/4
predicate (F-N-A-B
in the golfed version) takes a number N
and two accumulators A
and B
(which should start at 0
and 1
) and unifies F
with the N
th Fibonacci number. If N
is 0
, F
is simply the current value of A
, the smaller accumulator value. Otherwise, count N
down by one and recurse with new accumulator values B
and A+B
.
fibindex/3
(F/N/I
in the golfed version) takes a Fibonacci number F
and an index I
(which should start at 0
) and unifies N
with the Fibonacci index of F
. Either F
is the I
th Fibonacci number, in which case N=I
and we're done, or we count I
up by one and recurse. Note that this approach leads to infinite recursion if given a non-Fibonacci number, but we don't have to handle that case for this challenge.
Finally, fibindex/2
(F/N
) just calls fibindex/3
with an initial I
value of 0
.
Regex (.NET), (削除) 23 (削除ここまで) 19 bytes
(2円?(1円)|x$|^x|\b)*
Takes its input in unary, as a string of x
characters whose length represents the number. Returns its output as the capture count of group 1円
.
This is based on Martin Ender's .NET regex for matching Fibonacci numbers. The .NET feature of balanced groups is used to count the number of iterations taken by the loop.
- That regex is first initially translated to use
x
as its unary numeral, yielding^$|^(^x|(?>2円?)(1円))*x$
. - Then the
x$
at the end is moved inside as the extra alternative|x$
, incrementing the loop count by \1ドル\$ for all \$n>0\$. This also allows us to remove the^$|
at the beginning, because^(^x|(?>2円?)(1円)|x$)*$
will now match \$n=0\$ on its own. (It will also now match numbers that are \0ドル\$ or \1ドル\$ less than a Fibonacci number, but we don't care because as specified by the challenge, all inputs will be Fibonacci numbers.) - Then the extra alternative
|\b
is added to increment the loop count again for all \$n>0\$;\b
cannot match on an input of \$n=0\$ because there is no word character ([0-9A-Za-z_]
) to form a boundary with the absense of a word character, but it will always match at the end of a string of one or morex
s. The match is zero-width, so the loop will then be terminated. - Then we remove the
^
and$
anchors sandwiching the regex, because we don't need to return a non-match for non-Fibonacci numbers. - Then an optimization for speed, moving the
^x
alternative as far to the end as possible, because it only has to match once, and would add a failed match to every subsequent iteration if ordered as the first alternative. - The
2円?
can lose the(?>
...)
atomic group around it, because we don't need to determine if a number is Fibonacci or not. Due to the lack of any assertions following the loop, it will simply keep the first match it finds at each iteration, not having any reason to backtrack.
27 byte version that matches iff the input is a Fibonacci number:
^((?>2円?)(1円)\B|x$|^x|\b)*$
The \B
prevents numbers \1ドル\$ less than a Fibonacci number from being matched; in unary, \B
matches at every place except the beginning and end in a non-zero number (and matches "everywhere" in an input of zero).
Regex 🐇
(PCRE1 / PCRE2 v10.34 or earlier), 20 bytes
^(2円?(1円)|x$|^x)+|^x
Try it online! - PCRE1
Try it online! - PCRE2 v10.33
Takes its input in unary, as the length of a string of x
s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)
This is a straight port of the .NET version to the 🐇
output format. It needs to be anchored, so that the only variation in how a match can happen is how many iterations the loop takes, not where in the string it starts. The *
is changed to +
because with the former, looping for 0 iterations would still be a match, and would result in a 1-indexed return value.
Moving the |\b
alternative to the end as |^x
is a minor speed optimization, at a zero-byte cost. As an added bonus, we can change this to |^xx
to return \1ドル\$ (instead of \2ドル\$) for an input of \1ドル\$.
For PCRE1, and PCRE2 before v10.35, the atomic group is not needed even with 🐇
-output, because those versions automatically atomicize groups that contain a nested backreference (in this case, 1円
).
Regex 🐇
(Perl / PCRE), 23 bytes
^(2円?+(1円)|^x)+|^x|^xxx
Try it online! - Perl v5.28.2 / Attempt This Online! - Perl v5.36+
Try it online! - PCRE1
Try it online! - PCRE2 v10.33 / Attempt This Online! - PCRE2 v10.40+
Try it online! - PCRE2 - every Fibonacci number up to \$F_{46}\$ in under 20 seconds
Instead of atomicizing the whole loop, as ^((?>2円?(1円)|x$|^x|\b))+
, we move all choices out of the loop, so there's only one thing it can do at any iteration. This saves 1 byte.
As in the PCRE1 version, we can change |^x
to |^xx
to return \1ドル\$ (instead of \2ドル\$) for an input of \1ドル\$.
An alternative 23 byte option would be ^(2円?+(1円)|x$|^x)+|^xxx
, but that'd be ever-so-slightly slower due to having an extra choice inside the loop.
Regex (.NET), (削除) 33 (削除ここまで) 29 bytes
(?=(^(x)|3円?(1円)|)*)(?<-1>x)*
Returns its output as the sum of the lengths of the match (group 0円
) and group 2円
. It is done as a sum because for inputs \$n=1,2,3\$ the Fibonacci index is \$n+1\$ and would not fit in a single capture group.
Group 2円
, which is (x)
in this regex, is captured as \1ドル\$ iff the loop takes at least one iteration, which happens for all \$n>0\$. The loop count itself is also given an extra increment, as in the 23 byte version above, by the addition of an empty alternative |
inside the loop. This will result in a zero-width match being taken at the end, regardless of input; it even happens for \$n=0\$, but that doesn't matter, because the (?<-1>x)*
will not have room to pop its capture, and the return match will be \0ドル\$ anyway.
Note that this regex would actually not be made shorter by returning its output as the sum of the lengths of 0円
, 3円
, and 3円
, as the shortest way I can think of to do that takes 34 bytes:
(?=((?>2円?)(1円)|^x)*(x))?(?<-1>x)*
38 byte version that matches iff the input is a Fibonacci number:
^(?=(^(x)|(?>3円?)(1円)|)*x$|$)(?<-1>x)*
Regex (Perl / PCRE), 31 bytes
((?=(2円?x))(^x|4円?+(3円)))*(x|^)
Try it online! - Perl
Try it online! - PCRE
Returns its output as the sum of the lengths of groups 2円
, 5円
, and 5円
. The regex saves 3 bytes just by using a possessive quantifier, replacing (?>4円?)
with 4円?+
.
The Fibonacci index minus \2ドル\$ is built up in 2円
using the expression (?=(2円?x))
. The first time this is hit, the 2円?
will evaluate to zero because 2円
isn't set yet, and 2円
will be given a value of \1ドル\$. On every subsequent iteration, it will be incremented. This is done in a lookahead to avoid influencing the running total Fibonacci match, and is safe because at every step, the index will be less than the amount added to the full match.
The (x|^)
at the end serves to let 5円
\$=1\$ in all cases except \$n=0\$.
This regex does not work under Java; group 2円
just captures \1ドル\$ and stays there. This may be due to a bug in Java's regex engine.
33 byte version that matches iff the input is a Fibonacci number:
^((?=(2円?x))(^x|4円?+(3円)))*(x|^)$
Try it online! - Perl
Try it online! - PCRE
If the output specification must be simplified to sum only two groups, this would be the shortest way I can think of doing it (39 bytes, output is the sum of the lengths of groups 0円
and 5円
):
(?=((?=(2円?x))(^x|4円?+(3円)))*(x))?2円?x?
Try it online! - Perl
Try it online! - PCRE
42 byte version that matches iff the input is a Fibonacci number:
^(?=((?=(2円?x))(^x|4円?+(3円)))*(x|^)$)2円?x?
Try it online! - Perl
Try it online! - PCRE
C, (削除) 62 (削除ここまで) 58 bytes
g(c,a,b){return c-a?g(c,b,a+b)+1:0;}f(c){return g(c,0,1);}
Detailed
int g(int c, int a, int b)
{
if (c == a)
{
return 0;
}
else
{
return g(c, b, a+b) + 1;
}
}
int f(c)
{
return g(c, 0, 1);
}
Java 7, 70 bytes
int c(int n){int a=0,b=1,c=0,t;while(a<n){c++;t=b;b+=a;a=t;}return c;}
-
2\$\begingroup\$ Welcome to PPCG, nice first answer! \$\endgroup\$Leaky Nun– Leaky Nun2016年07月24日 07:20:06 +00:00Commented Jul 24, 2016 at 7:20
-
\$\begingroup\$
int c(int n){int a=0,b=1,c=0,t;for(;a<n;t=b,b+=a,a=t)c++;return c;}
(not tested) \$\endgroup\$Leaky Nun– Leaky Nun2016年07月24日 07:21:08 +00:00Commented Jul 24, 2016 at 7:21 -
\$\begingroup\$
int c(int n){int a=0,b=1,c=0;while(a<n){c++;b+=a;a=b-a;}return c;}
(not tested) \$\endgroup\$Leaky Nun– Leaky Nun2016年07月24日 07:31:56 +00:00Commented Jul 24, 2016 at 7:31 -
2\$\begingroup\$
int c(int n){int a=0,b=1,c=0;for(;a<n;b+=a,a=b-a)c++;return c;}
(not tested) \$\endgroup\$Leaky Nun– Leaky Nun2016年07月24日 07:32:22 +00:00Commented Jul 24, 2016 at 7:32
TSQL, 143 bytes
Input goes in @n
as in DECLARE @n INT = 1836311903;
DECLARE @O BIGINT=0;WITH F(R,P,N)AS(SELECT @O,@O,@O+1 UNION ALL SELECT R+1,N,P+N FROM F WHERE N<=@n)SELECT MAX(R)FROM F OPTION(MAXRECURSION 0);
Haskell, 45 bytes
f x=round$log(sqrt 5*x+0.9)/log((sqrt 5+1)/2)
Java 7, 89 bytes
int c(int n){int i=-1;while(f(++i)<n);return i;}int f(int n){return n<2?n:f(n-1)+f(n-2);}
Inspired by the explanation of @Adnan's 05AB1E answer.
Ungolfed & test cases:
Try it here. (Time limit exceeded for last test case, but it works in about 30-45 seconds on my PC.)
class Main{
static int c(int n){
int i = -1;
while(f(++i) < n);
return i;
}
static int f(int n){
return n < 2
? n
: f(n - 1) + f(n - 2);
}
public static void main(String[] a){
System.out.println(c(0));
System.out.println(c(2));
System.out.println(c(3));
System.out.println(c(5));
System.out.println(c(8));
System.out.println(c(1836311903));
}
}
Output:
0
3
4
5
6
46
Sesos, 28 bytes
Hexdump:
0000000: 16f8be 766ef7 ae6d80 f90bde b563f0 7ded18 3ceffa ...vn..m.....c.}..<..
0000015: b1c1bb af9f3f ff .....?.
(Exponential time because in Sesos copying a number needs exponential time.)
Assembly used to generate the binary file:
set numin
set numout
get
jmp
sub 1
fwd 1
add 1
fwd 1
add 1
rwd 2
jnz ;input input
fwd 4
add 1 ;input input 0 1
fwd 2
add 1 ;input input 0 1 0 1
rwd 4
jmp
jmp ;input input-curr curr next iterations
sub 1
jnz ;input 0 curr next iterations
fwd 3
add 1
jmp
sub 1
fwd 2
add 1
rwd 2
jnz ;input 0 curr next 0 0 iterations+1
rwd 1
jmp
sub 1
fwd 1
add 1
fwd 1
add 1
rwd 2
jnz ;input 0 curr 0 next next iterations+1
rwd 1
jmp
sub 1
fwd 1
sub 1
fwd 2
add 1
rwd 3
jnz ;input 0 0 -curr next curr+next iterations+1
rwd 2
jmp
sub 1
fwd 2
add 1
fwd 1
add 1
rwd 3
jnz ;0 0 input input-curr next curr+next iterations+1
fwd 3
jnz
fwd 3
put
Java 8 61 bytes
Same as @dainichi answer only made shorter by using Java 8 lambdas. The answer is a valid rvalue expression.
n->{int a=0,b=1,c=0,t;while(a<n){c++;t=b;b+=a;a=t;}return c;}
Ungolfed:
interface F
{
int c(int n);
}
public class Main
{
public static void main(String[] args)
{
F f = n->{int a=0,b=1,c=0,t;while(a<n){c++;t=b;b+=a;a=t;}return c;};
}
}
Brachylog, 14 bytes
≜∧0;1⟨t≡+⟩i↖?h
Takes input through the output variable and outputs through the input variable.
≜ Label the input variable, trying 0, 1, -1, 2...,
0 then starting with 0
∧ (which is not necessarily the input variable)
;1 paired with 1,
⟨t≡ ⟩ replace the first element of the pair with the last element
⟨ ≡+⟩ and the last element of the pair with the sum of the elements
i↖? a number of times equal to the input variable,
h such that the first element of the pair is the output variable.
I'm not entirely sure why ≜
is necessary.
-
3\$\begingroup\$ I think four months is longer than "soon" \$\endgroup\$The Fifth Marshal– The Fifth Marshal2021年04月26日 00:25:49 +00:00Commented Apr 26, 2021 at 0:25
Vyxal, (削除) 6 (削除ここまで) 4 bytes
ÞFḟ›
-2 thanks to Deadcode
1 byte longer than it should be just because Vyxal's "Fibonacci sequence" builtin does not start with 0.
-
1
-
\$\begingroup\$ You forgot to change the code in the code block. \$\endgroup\$naffetS– naffetS2022年07月29日 02:26:57 +00:00Commented Jul 29, 2022 at 2:26
x86-64 machine code, System V calling convention, 16 bytes
31 c0 99 6a 01 59 0f c1 d1 ff c0 39 fa 75 f7 c3
In assembly:
fib:
# initialize registers: rax=0, rdx=0, rcx=1
xor eax,eax
cdq
push 1
pop rcx
fib_loop:
# add registers and swap over and over
# until the result equals the input
xadd ecx,edx
inc eax
cmp edx,edi
jne fib_loop
ret
Explicitly computes the nth Fibonacci number in ecx
and edx
, while keeping track of the count in eax
. Takes input in rdi
and returns in rax
, as usual for 64-bit x86.
Though it wasn't required for the challenge, this works on all 64-bit Fibonacci numbers as well. Somewhat coincidentally, as it only works since none of them are equal to each other modulo 2^32
.
1
appears only once. Sort of like howarcsin(x)
is considered to be the inverse ofsin(x)
, even thoughsin(x)
is not injective (or even surjective) in and of itself. It's all about that context! \$\endgroup\$