# 斐波那契反转！

42

0是有效的输入和输出。

## 测试用例

``````0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
``````

39

Michael

19

6
@Michael这不是斐波纳契函数的反函数，因为斐波那契函数没有反函数，因为它不是单射的（因为“ 1”出现两次）。反向最初来自“反向表查找”的想法，这是我希望人们在这里所做的事情（例如，我希望他们这样做是为了解决问题）。
SEJPM

9

1
@SEJPM：不过，我确实期望完成一个任务，例如“编写一个向后拼写斐波那契序列的程序”。
Bergi '16

58

## 实际上是1个字节

``````f
``````

``````╗1`F╜=`╓i
``````

``````╗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
``````

15

37

19
@Fatalize Fibonacci和反Fibonacci函数是我添加的第一个函数。即使到现在，仍然有39个完全未使用的单字节命令（谁知道可以利用多少个重载）。256个符号，加上实际上有5种类型（整数，实数，字符串，可迭代，函数）的事实，意味着最多有1280个可能的一元函数和6400个可能的二进制函数。对于看似无用的命令，还有很多空间。
Mego

23
@Mego您是否只是想与Mathematica竞争最强大的功能？
gcampbell '16

13

nicael

42

# Mathematica，25个字节

``````InverseFunction@Fibonacci
``````

31

# Python，36 34 32字节

``lambda n:len(str(66*n**6))//1.24``

### 之前的版本：

``````f=lambda n:len(str(66*n**6))//1.24
f=lambda n:(n*n*7).bit_length()//1.4``````

## 说明

``fibonacci(n) ~ ( (1 + sqrt(5)) / 2)**n / sqrt(5)``

``log fibonacci(n) ~ n log((1 + sqrt(5)) / 2) - log(sqrt(5))``

``f(n) ~ (log(n) + log(sqrt(5))) / log((1 + sqrt(5))/2)``

• 用于`len(str(n))`在不导入的情况下计算日志库10 `log`（用于`.bit_length()`计算日志库2的旧版本）
• 提高`n`到幂，以便对数的近似值可以区分连续的斐波那契数
• 乘以一个常数会放大这些值，以使它们在正确的范围内

Leaky Nun

2

19

# 05AB1E，3个字节

``````ÅFg
``````

``````ÅF   # Generate all Fibonacci numbers <= input.
g  # Get the length of this list.
``````

10

# 果冻，14 11个字节

``````5½×lØp+.Ḟ»0
``````

``````   lØp      # Log Base phi
5½          # Of the square root of 5
×         # Times the input
+     # Plus
.    # 0.5
Ḟ   # Floored
``````

``````»      # The maximum of
0     # Zero
# And the previous calculated value.
``````

7
+1是因为对说明的评论是打油诗的结尾。

10

# 朱莉娅27 26 18字节

``!n=log(3n+.7)÷.48``

### 这个怎么运作

Binet的公式规定如下。  • logφ= 0.481211825059603447…≈0.48

不幸的是，0.5不够精确。

• √5= 2.2360679774997896964…≈3

乍一看，这似乎是一个可怕的近似值，但是我们采用对数，因为log 3-log√5= 0.29389333245105…，所以四舍五入前的结果将有一个小的常数因子。

• 0.5≈0.7

由于前一个近似值有余，因此我们实际上可以完全省略此项，并且对于F> 0仍然可以获得正确的结果。但是，如果F = 0，对数将是不确定的。0.7是使公式扩展为F = 0的最短值。

8

# JavaScript，54 50 69 50 42字节

``````b=>(j=>{for(i=c=0;b-i;c++)i=j+(j=i)})(1)|c
``````

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

edc65

1
@edc哇，这很聪明，谢谢<3
nicael '16

8

# Perl 6  33 30  27字节

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

### 说明：

``````# 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
}``````

### 测试：

``````#! /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,*+*...*)), &[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

smls

Jo King

7

# 果冻，8 字节

``````1+Ð¡0
¢i
``````

### 这个怎么运作

``````¢i     Main link. Argument: n

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

6

## Pyke，5个字节

``````.f.bq
``````

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

5

## Python，29个字节

``g=lambda n:n>.7and-~g(n/1.61)``

``g=lambda n:n//.7and 1+g(n/1.61)``

4

## JavaScript（ES6），39 33字节

``````f=(n,j=0,k=1)=>n>j?f(n,k,j+k)+1:0
``````

``````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
``````

@charlie对不起，我总是忘记了这一点。固定。

4

## Sage，49个字节

``lambda x,s=sqrt(5):x and int(log(x*s,(1+s)/2)+.5)``

Python用户可能想知道为什么要使用我的`sqrt(5)`而不是简称的`5**.5`-这是因为它`5**.5`是使用C `pow`函数计算的，并且由于浮点问题而失去了精度。Sage中重载了许多数学函数（包括`sqrt``log`），以返回精确的符号值，而这不会失去精度。

Yttsi '16

4

# MATL，14个字节

``````t?5X^*17L&YlYo
``````

F表示第n个斐波那契数，而φ表示黄金分割率。然后 • 该代码没有加1/2而是四舍五入，而是简单地四舍五入为最接近的整数，该整数占用更少的字节。
• 输入F = 0需要作为特殊情况处理。

### 怎么做

``````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

DJMcMayhem

@ jimmy23013不错的方法！您应该明确地将其发布为一个单独的答案
Luis Mendo

jimmy23013

3

# Python，38个字节

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

Ideone上进行测试

3

## JavaScript，22个字节

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

@Dennis：在JS中，按位运算符仅占用最后32位和`-Infinity = FFF00000 00000000`。我很高兴发现它，因为不必像那样预先设置一个明确的零测试，所以节省了3个字节`n&&`。除此之外，的主要目的`|0`是替代它`Math.trunc()`（例如`÷`Julia）。

3

# C，62 58字节

``g(c,a,b){return c-a?g(c,b,a+b)+1:0;}f(c){return g(c,0,1);}``

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

3

# Java 7，70个字节

``````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

2

Leaky Nun

`int c(int n){int a=0,b=1,c=0,t;for(;a<n;t=b,b+=a,a=t)c++;return c;}`（未经测试）
Leaky Nun

`int c(int n){int a=0,b=1,c=0;while(a<n){c++;b+=a;a=b-a;}return c;}`（未经测试）
Leaky Nun

2
`int c(int n){int a=0,b=1,c=0;for(;a<n;b+=a,a=b-a)c++;return c;}`（未测试）
Leaky Nun

2

## TSQL，143字节

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

2

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

2

# Sesos，28个字节

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

（指数时间，因为在Sesos中复制数字需要指数时间。）

``````set numin
set numout
get
jmp
sub 1
fwd 1
fwd 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
jmp
sub 1
fwd 2
rwd 2
jnz    ;input 0 curr next 0 0 iterations+1
rwd 1
jmp
sub 1
fwd 1
fwd 1
rwd 2
jnz    ;input 0 curr 0 next next iterations+1
rwd 1
jmp
sub 1
fwd 1
sub 1
fwd 2
rwd 3
jnz    ;input 0 0 -curr next curr+next iterations+1
rwd 2
jmp
sub 1
fwd 2
fwd 1
rwd 3
jnz    ;0 0 input input-curr next curr+next iterations+1
fwd 3
jnz
fwd 3
put``````

2

# Java 8 61字节

``````n->{int a=0,b=1,c=0,t;while(a<n){c++;t=b;b+=a;a=t;}return c;}
``````

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

1

# Pyth，13个字节

``````J1tf>=Z+~JZZQ
``````

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

### 替代方法，18字节

``````L?<b2bsyMtBtbs.IyG
``````

`.I`用于逆。

1

# Java 7，89个字节

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

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

``````0
3
4
5
6
46
``````

1

## Perl 5.10，48个字节

`-a` 开关增加一个字节。

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

1

# J，32 27 17字节

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

## 用法

``````   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
``````

## 说明

``````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
``````

1

# Mathematica，30个字节

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

1

# Japt，10字节

``````Lo æ@U¥MgX
``````

## 说明

``````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
``````

1

# Brachylog，14个字节

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

``````≜                 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.
``````

0

## Javascript（使用外部库）（84字节）

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