Fibonacci reversed!

42

7

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

SEJPM

Posted 2016-07-17T19:46:05.547

Reputation: 3 203

39

Slight nit-pick: shouldn't this be considered inverse fibonacci https://en.m.wikipedia.org/wiki/Inverse_function

– Michael – 2016-07-18T00:17:06.013

19So, iccanobiF?! – None – 2016-07-18T11:24:27.933

6@Michael this is not inverse Fibonacci, because there's no inverse to Fibonacci function because it is not injective (because the "1" appears twice). The reverse originally came from the idea of "reverse table look-ups" which is what I expected people to do here (e.g. I expected them to do it to solve the problem). – SEJPM – 2016-07-18T14:19:56.290

9

The function here could be considered a right inverse of the "Fibonacci function" from the non-negative integers to the set of Fibonacci numbers. The existence of a right inverse does not imply injectivity.

– Dennis – 2016-07-18T17:31:34.197

@MatthewRoh Already Taken. I already did that. :P

– mbomb007 – 2016-07-18T19:26:54.350

1@SEJPM: I kinda did expect a task like "write a program that spells out the fibonacci sequence backwards", though. – Bergi – 2016-07-20T03:58:32.570

@SEJPM: It is if you limit its domain so that 1 appears only once. Sort of like how arcsin(x) is considered to be the inverse of sin(x), even though sin(x) is not injective (or even surjective) in and of itself. It's all about that context! – Tim Čas – 2016-08-31T22:10:21.380

Answers

58

Actually, 1 byte

f

Yes, there's a builtin for this, since November 16, 2015.

Try it online


For fun, without the builtin, it's 9 bytes:

╗1`F╜=`╓i

Try it online!

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

Mego

Posted 2016-07-17T19:46:05.547

Reputation: 32 998

15I have one thought and one thought only when I see this: ಠ_ಠ – Addison Crump – 2016-07-17T19:51:38.413

37I don't really understand why you would "waste" a symbol for such a ridiculously specific purpose – Fatalize – 2016-07-17T19:54:15.543

19@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. – Mego – 2016-07-17T19:56:24.940

23@Mego Are you just trying to compete with Mathematica for the most builtins? – gcampbell – 2016-07-18T10:07:17.657

13Actually, it's just a byte... lol, love this language name. – nicael – 2016-07-18T20:45:22.193

6Now we have to invent a language where an empty file means inverse Fibonacci to triumph this. – IllidanS4 wants Monica back – 2016-07-19T11:01:03.733

42

Mathematica, 25 bytes

InverseFunction@Fibonacci

Function. Pretty self-explanatory if you ask me.

LegionMammal978

Posted 2016-07-17T19:46:05.547

Reputation: 15 731

31

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 importing log (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.

user16488

Posted 2016-07-17T19:46:05.547

Reputation:

it should be 32 bytes, because f= is not counted. – Leaky Nun – 2016-07-18T06:07:43.390

2

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.

– Dennis – 2016-07-18T06:46:19.117

19

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!.

Adnan

Posted 2016-07-17T19:46:05.547

Reputation: 41 965

10

Jelly, 14 11 bytes

5½×lØp+.Ḟ»0

Try it online!

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
5½          # 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.

James

Posted 2016-07-17T19:46:05.547

Reputation: 54 537

7+1 because the comments on the explanation are the end of a limerick. – Daniel – 2016-07-18T21:05:42.107

10

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.

Try it online!

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… &approx; 0.48

    Unfortunately, 0.5 isn't precise enough.

  • √5 = 2.2360679774997896964… &approx; 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 &approx; 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.

Dennis

Posted 2016-07-17T19:46:05.547

Reputation: 196 637

8

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.

nicael

Posted 2016-07-17T19:46:05.547

Reputation: 4 585

simple b=>{for(j=1,i=c=0;b-i;c++)i=j+(j=i);return c} 45, golfed b=>(j=>{for(i=c=0;b-i;c++)i=j+(j=i)})(1)|c 42. – edc65 – 2016-07-17T20:51:39.257

1@edc Wow, that's clever, thanks <3 – nicael – 2016-07-17T22:05:26.090

8

Perl 6  33 30  27 bytes

{first *==$_,:k,(0,1,*+*...*>$_)}
{first *==$_,:k,(0,1,*+*...*)}
{first $_,:k,(0,1,*+*...*)}

Try it

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

Brad Gilbert b2gills

Posted 2016-07-17T19:46:05.547

Reputation: 12 713

1You can replace first *==$_ with just first $_, because a number is a valid smart-matcher. – smls – 2017-02-27T18:43:54.973

24 bytes by using the ... operator instead of first – Jo King – 2019-08-28T22:56:27.937

7

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.

Dennis

Posted 2016-07-17T19:46:05.547

Reputation: 196 637

6

Pyke, 5 bytes

.f.bq

Try it here!

.f    - first number where
  .b  -  fib(n)
    q - ^ == input

Blue

Posted 2016-07-17T19:46:05.547

Reputation: 26 661

5

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)

xnor

Posted 2016-07-17T19:46:05.547

Reputation: 115 687

4

MATL, 14 bytes

t?5X^*17L&YlYo

Try it online!

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

enter image description here

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

Luis Mendo

Posted 2016-07-17T19:46:05.547

Reputation: 87 464

1Alternate approach: O1G:"yy+]vGmfq – James – 2016-07-18T22:06:06.337

1

11 bytes: t?17L&YlXkQ

– jimmy23013 – 2019-08-31T08:47:18.103

@jimmy23013 Nice approach! You should definiely post that as a separate answer – Luis Mendo – 2019-08-31T10:42:37.707

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.

– jimmy23013 – 2019-08-31T17:12:01.927

4

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.

Try it online.

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.

Mego

Posted 2016-07-17T19:46:05.547

Reputation: 32 998

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 typing sqrt(5) twice? – Yytsi – 2016-07-18T11:27:13.193

4

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

Neil

Posted 2016-07-17T19:46:05.547

Reputation: 95 035

Just distribute the log and precompute all constants... – charlie – 2016-07-19T17:33:00.287

IMHO, if you call recursively the lambda by name, f(n,k,j+k), you should include the assignment f= and count it as +2 bytes. The rule for unnamed lambdas should not apply here. – charlie – 2016-07-21T12:48:42.020

@charlie Sorry, I always forgot about that. Fixed. – Neil – 2016-07-21T13:27:38.093

3

Python, 38 bytes

f=lambda n,a=0,b=1:n^a and-~f(n,b,a+b)

Test it on Ideone.

Dennis

Posted 2016-07-17T19:46:05.547

Reputation: 196 637

3

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);
}

Khaled.K

Posted 2016-07-17T19:46:05.547

Reputation: 1 435

3

JavaScript, 22 bytes

n=>Math.log(n)/.48+2|0

charlie

Posted 2016-07-17T19:46:05.547

Reputation: 171

I didn't think this would work when I saw it, but apparently -Infinity|0 is 0 in JavaScript. Go figure. – Dennis – 2016-07-20T16:43:16.587

@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 like n&&. Apart from that, the main purpose of |0 is a substitute for Math.trunc() (like ÷ in Julia). – charlie – 2016-07-21T12:38:58.703

3

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;}

https://ideone.com/I4rUC5

dainichi

Posted 2016-07-17T19:46:05.547

Reputation: 131

2Welcome to PPCG, nice first answer! – Leaky Nun – 2016-07-24T07:20:06.933

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) – Leaky Nun – 2016-07-24T07:21:08.797

int c(int n){int a=0,b=1,c=0;while(a<n){c++;b+=a;a=b-a;}return c;} (not tested) – Leaky Nun – 2016-07-24T07:31:56.243

2int c(int n){int a=0,b=1,c=0;for(;a<n;b+=a,a=b-a)c++;return c;} (not tested) – Leaky Nun – 2016-07-24T07:32:22.013

2

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

Liesel

Posted 2016-07-17T19:46:05.547

Reputation: 241

2

Haskell, 45 bytes

f x=round$log(sqrt 5*x+0.9)/log((sqrt 5+1)/2)

Damien

Posted 2016-07-17T19:46:05.547

Reputation: 2 407

2

Sesos, 28 bytes

Hexdump:

0000000: 16f8be 766ef7 ae6d80 f90bde b563f0 7ded18 3ceffa  ...vn..m.....c.}..<..
0000015: b1c1bb af9f3f ff                                  .....?.

Try it online!

(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

Leaky Nun

Posted 2016-07-17T19:46:05.547

Reputation: 45 011

2

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;};
    }
}

BananyaDev

Posted 2016-07-17T19:46:05.547

Reputation: 41

1

Japt, 10 bytes

Lo æ@U¥MgX

Try it online!

Explanation

Lo æ@U¥MgX
Lo           // Creates a range from 0 to 99
   æ@        // Iterates through the range. Returns the first item X where:
     U¥      //   Input ==
       MgX   //   Xth Fibonacci number

Oliver

Posted 2016-07-17T19:46:05.547

Reputation: 7 160

1

Brachylog, 14 bytes

≜∧0;1⟨t≡+⟩ⁱ↖?h

Try it online!

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
          ⁱ↖?     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.

Unrelated String

Posted 2016-07-17T19:46:05.547

Reputation: 5 300

1

Pyth, 13 bytes

J1tf>=Z+~JZZQ

Test suite.

Approximation in Python 2:

Z=0;J=1;T=1;Q=input()
while not J+Z>Q:
    temp=J
    J=Z
    Z=temp+J
    T += 1
print(T-1)

alternative approach, 18 bytes

L?<b2bsyMtBtbs.IyG

Test suite.

This uses .I for inverse.

Leaky Nun

Posted 2016-07-17T19:46:05.547

Reputation: 45 011

1

J, 32 27 17 bytes

i.~0,+/@(!|.)\@i.

Computes the first n Fibonacci numbers and then finds the index of n in that list.

Usage

Extra commands are used for formatting multiple input/output. The last test case is omitted since it will require much more time to compute.

   f =: i.~0,+/@(!|.)\@i.
   (,.f"0) 0 1 2 3 5 8 13
 0 0
 1 1
 2 3
 3 4
 5 5
 8 6
13 7

Explanation

i.~0,+/@(!|.)\@i.  Input: n
               i.  Get the range [0, 1, ..., n-1]
             \@    For each prefix of that range
          |.         Reverse the prefix
         !           Find the binomial coefficient between each value in the original
                     prefix and the reversed prefix
     +/@             Sum those binomial coefficients
                   This will create the Fibonacci numbers from 1 to n
   0,              Prepend a 0 to the list of Fibonacci numbers
i.~                Find the index of n in that list and return

miles

Posted 2016-07-17T19:46:05.547

Reputation: 15 654

1

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

Kevin Cruijssen

Posted 2016-07-17T19:46:05.547

Reputation: 67 575

1

Perl 5.10, 48 bytes

Basically looking for the right n so that F(n) = input.

-a switch adds one byte.

$b++;while($_>$a){$c=$a;$a+=$b;$b=$c;$n++}say$n

Try it here!

Paul Picard

Posted 2016-07-17T19:46:05.547

Reputation: 863

1

Mathematica, 30 bytes

Round@Log[5^.5/2+.5,.8+5^.5#]&

Pure function; returns 2 if the input is 1.

Doesn't beat the other Mathematica entry, but showcases an unusual method: It's a (very cool) fact that the Nth Fibonacci number is the closest integer to [1/sqrt(5) times the Nth power of the golden ratio] ("Binet's formula").

Therefore the inverse function will be the base-[golden ratio] logarithm of [sqrt(5) times the Fibonacci number in question]. The .8+ is a hack to make sure we don't take the logarithm of 0, without screwing up the other values.

Greg Martin

Posted 2016-07-17T19:46:05.547

Reputation: 13 940

0

AWK, 58 bytes

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

Try it online!

Robert Benson

Posted 2016-07-17T19:46:05.547

Reputation: 1 339

0

Javascript (using external library) (84 bytes)

n=>_.Until((i,a)=>{l=a.length;if(a[l-1]!=n){return i<=1?i:a[l-1]+a[l-2]}}).Count()-1

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Library has static method that creates a sequence until the predicate has an undefined return value. The predicate has a signature of ("i"ndex, current internal "a"rray generated). At each iteration, we check if the last element of the internal array is equal to the input, n. If not, return the next value in the fib sequence. Otherwise, the predicate has an undefined result which terminates the generation of the sequence. Then, we return the length of the sequence (and subtract 1 in order to comply with the 0 based-ness as seen in the OP

enter image description here

applejacks01

Posted 2016-07-17T19:46:05.547

Reputation: 989

53 Bytes by using code from here n=>{a=c=t=0,b=1;while(a<n){c++;t=b;b+=a;a=t}return c} Try it online!

– pixma140 – 2019-08-29T13:17:08.707

0

Jelly, 9 bytes

‘RḶUc$S€i

Finds the first n+1 Fibonacci numbers and locates the index of n in that list.

Note: This is very inefficient and large test cases should not be run on the online interpreter.

Try it here.

Explanation

‘RḶUc$S€i  Input: n
‘          Increment n
 R         Generate the range [1, 2, ..., n+1]
           For each value x in that range
  Ḷ          Create the range [0, 1, ..., x-1]
   U         Create a reversed copy
    c        Compute the binomial coefficient between each pair of values
     $       Combine the last two links (Uc) as a monad
      S€   Sum each list of binomial coefficients
           This will result in a list of the first n+1 Fibonacci numbers
        i  Find the index of n in that list and return

miles

Posted 2016-07-17T19:46:05.547

Reputation: 15 654

0

C#, 130 Bytes

Golfed:

int F(int n){var a=new int[4];a[1]=1;int i=0;while(a[3]<n){a[3]=a.ToList().GetRange(1,2).Sum();a[1]=a[2];a[2]=a[3];i++;}return i;}

Ungolfed:

public int F(int n)
{
  var a = new int[4];

  a[1] = 1;

  int i = 0;

  while (a[3] < n)
  {
    a[3] = a.ToList().GetRange(1, 2).Sum();

    a[1] = a[2];
    a[2] = a[3];

    i++;
  }

  return i;
}

Test:

var fibonacciReversed = new FibonacciReversed();

var fr = fibonacciReversed.F(0);
Console.WriteLine(fr);
0

fr = fibonacciReversed.F(2);
Console.WriteLine(fr);
3

fr = fibonacciReversed.F(3);
Console.WriteLine(fr);
4

fr = fibonacciReversed.F(5);
Console.WriteLine(fr);
5

fr = fibonacciReversed.F(8);
Console.WriteLine(fr);
6

fr = fibonacciReversed.F(13);
Console.WriteLine(fr);
7

fr = fibonacciReversed.F(1836311903);
Console.WriteLine(fr);
46

Pete Arden

Posted 2016-07-17T19:46:05.547

Reputation: 1 151

0

Groovy, 38 bytes

{a=c=0;b=1;for(;a<it;b+=(a=b-a))c++;c}

Magic Octopus Urn

Posted 2016-07-17T19:46:05.547

Reputation: 19 422

0

Perl, 33 +1 = 34 bytes

Run with the -p flag

$_=int log(.5+$_*5**.5)/log 1.618

The code uses an approximation of the golden ratio as 1.618, and calculates the index using the following formula:

Fibonacci index formula

Gabriel Benamy

Posted 2016-07-17T19:46:05.547

Reputation: 2 827