44
\$\begingroup\$

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
\$\endgroup\$
7
  • 41
    \$\begingroup\$ Slight nit-pick: shouldn't this be considered inverse fibonacci en.m.wikipedia.org/wiki/Inverse_function \$\endgroup\$
    – Michael
    Jul 18, 2016 at 0:17
  • 21
    \$\begingroup\$ So, iccanobiF?! \$\endgroup\$
    – user54200
    Jul 18, 2016 at 11:24
  • 8
    \$\begingroup\$ @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). \$\endgroup\$
    – SEJPM
    Jul 18, 2016 at 14:19
  • 11
    \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    Jul 18, 2016 at 17:31
  • 1
    \$\begingroup\$ @SEJPM: I kinda did expect a task like "write a program that spells out the fibonacci sequence backwards", though. \$\endgroup\$
    – Bergi
    Jul 20, 2016 at 3:58

43 Answers 43

1
2
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Groovy, 38 bytes

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

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
\$\endgroup\$
1
\$\begingroup\$

Jelly, 5 bytes

‘ÆḞ€i

Try it online!

Nothing special here, just an updated version of Jelly

How it works

‘ÆḞ€i - Main link. Takes n on the left
‘     - Yield n+1
   €  - For each k = 1, 2, ..., n+1:
 ÆḞ   -   Yield the k'th Fibonacci number
    i - Return the index of n in this list
\$\endgroup\$
1
\$\begingroup\$

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

Try it online!

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ 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! \$\endgroup\$
    – pixma140
    Aug 29, 2019 at 13:17
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

Factor + project-euler.002, 23 22 bytes

[ dup fib-upto index ]

Try it online!

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.