逆斐波那契算法?
对于任意 n 计算 F(n) 的方法有数十种,其中许多方法都具有很高的运行时间和内存使用率。
然而,假设我想问相反的问题:
给定 F(n),n > 2、n是什么?
(n > 2 限制存在,因为 F(1) = F(2) = 1 并且没有明确的逆)。
解决这个问题最有效的方法是什么?通过枚举斐波那契数并在达到目标数时停止,可以很容易地在线性时间内完成此操作,但是有没有比这更快的方法呢?
编辑:目前,这里发布的最佳解决方案使用 O(log n) 内存在 O(log n) 时间内运行,假设数学运算在 O(1) 中运行并且机器字可以容纳任何O(1) 空间中的数字。我很好奇是否可以降低内存要求,因为您可以使用 O(1) 空间计算斐波那契数。
There are dozens of ways of computing F(n) for an arbitrary n, many of which have great runtime and memory usage.
However, suppose I wanted to ask the opposite question:
Given F(n) for n > 2, what is n?
(The n > 2 restriction is in there since F(1) = F(2) = 1 and there's no unambiguous inverse).
What would be the most efficient way of solving this problem? It's easy to do this in linear time by enumerating the Fibonacci numbers and stopping when you hit the target number, but is there some way of doing this any faster than that?
EDIT: currently, the best solution posted here runs in O(log n) time using O(log n) memory, assuming that mathematical operations run in O(1) and that a machine word can hold any number in O(1) space. I'm curious if it's possible to drop the memory requirements, since you can compute Fibonacci numbers using O(1) space.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
由于OP询问了不涉及任何浮点计算的矩阵解,所以它就是。假设数字运算具有
O(1)
复杂度,我们可以通过这种方式实现O(logn)
复杂度。让我们采用具有以下结构的 2x2 矩阵
A
现在考虑向量
(8, 5)
,存储两个连续的斐波那契数。如果将其乘以该矩阵,您将得到(8*1 + 5*1, 8*1 + 5*0) = (13, 8)
- 下一个斐波那契数。如果我们概括的话,
A^n * (1, 0) = (f(n), f(n - 1))
。实际的算法需要两个步骤。
A^2
、A^4
、A^8
等,直到我们通过所需的数字。n
进行二分查找。附带说明一下,任何形式为
f(n) = k1*f(n-1) + k2*f(n-2) + k3*f(n-3) + .. + kt* 的序列f(nt)
可以这样表示。Since OP has asked about matrix solution not involving any floating point computations, here it is. We can achieve
O(logn)
complexity this way, assuming numeric operations haveO(1)
complexity.Let's take 2x2 matrix
A
having following structureNow consider vector
(8, 5)
, storing two consecutive fibonacci numbers. If you multiply it by this matrix, you'll get(8*1 + 5*1, 8*1 + 5*0) = (13, 8)
- the next fibonacci number.If we generalize,
A^n * (1, 0) = (f(n), f(n - 1))
.The actual algorithm takes two steps.
A^2
,A^4
,A^8
, etc. until we pass desired number.n
, using calculated powers ofA
.On a side note, any sequence of the form
f(n) = k1*f(n-1) + k2*f(n-2) + k3*f(n-3) + .. + kt*f(n-t)
can be presented like this.Wikipedia 给出的结果为
Phi 是黄金比例。
Wikipedia gives the result as
where Phi is the golden ratio.
如果您可以轻松地用二进制解释 F(n),
您可能会对常数 1.7 和 1.1 表示怀疑。这些之所以有效,是因为 d*1.44042009041... + C 永远不会非常接近整数。
如果有兴趣的话,我明天可以发布推导。
下面是一个 n = 2 到 91 的表格,显示了向下取整之前的公式结果:
推导
α = log 2/log Φ ≈ 1.44042 所需的精度...
If you can easily interpret F(n) in binary,
You may be suspicious of the constants 1.7 and 1.1. These work because d*1.44042009041... + C never gets very close to an integer.
I can post a derivation tomorrow if there is interest.
Here is a table with n = 2 through 91, which shows the formula result before flooring:
Derivation
Required Precision for α = log 2/log Φ ≈ 1.44042...
通过计算无界单词来测量内存使用情况有点愚蠢,但只要这是模型,就会有一个 O(log n) 时间、O(1) 个单词 解决方案,类似于 Nikita Rybak 的解决方案,本质上是计算
n
通过其 Zeckendorf 表示,它基于斐波那契数列 (YO DAWG)。矩阵
定义满足以下条件的
: 我们将使用序列
A^F(k)
,而不是序列A^(2^k)
。后一个序列具有这样的属性:我们可以通过矩阵乘法向前移动,通过矩阵求逆和乘法向后移动,
因此我们可以仅使用
eightsix12 个单词构建双向迭代器假设我们将一切都存储为有理数(以避免假设存在单位成本鸿沟)。剩下的就是调整这个 O(1) 空间算法来寻找 Zekendorf 表示。Measuring memory usage by counting unbounded words is sort of silly, but as long as that's the model, there's an O(log n) time, O(1) word solution similar to Nikita Rybak's that in essence computes
n
via its Zeckendorf representation, which is based on the Fibonacci numbers (YO DAWG).Define the matrix
which satisfies
Instead of the sequence
A^(2^k)
, we're going to use the sequenceA^F(k)
. The latter sequence has the property that we can move forward with a matrix multiplyand backward with a matrix inverse and multiplication
so we can build a bidirectional iterator with only
eightsixtwelve words assuming we store everything as rationals (to avoid assuming the existence of a unit-cost divide). The rest is just adapting this O(1)-space algorithm for finding a Zeckendorf representation.已证明 fib n 的公式为
fib(n) = ( (phi)^n - (-phi)^(-n) ) / sqrt(5)
其中phi = (1+sqrt(5)) / 2,黄金分割数。 (请参阅此链接)。
您可以尝试找到上面 fib 函数的数学逆函数,或者以 32/64 次操作进行二分搜索(取决于可搜索的最大值有多大),以找到与该数字匹配的 n(通过计算 fib 来尝试每个 n (n) 并根据 fib(n) 与给定斐波那契数的比较将样本空间一分为二)。
编辑:@rcollyer 的解决方案更快,因为我的解决方案是 O(lg n) 而他找到的解决方案是 O(1) = 常数时间。
It's been proven that the formula for a fib n is
fib(n) = ( (phi)^n - (-phi)^(-n) ) / sqrt(5)
wherephi = (1+sqrt(5)) / 2
, the golden section number. (see this link).You could try to find a mathematical inverse to the fib function above, or otherwise do a binary search in 32/64 operations (depending on how big your searchable maximum is) to find the n that matches the number (try each n by computing fib(n) and splitting your sample space in two according to how fib(n) compares to the given fibonacci number).
Edit: @rcollyer's solution is faster, as mine is in O(lg n) and the one he found is in O(1) = constant time.
所以我正在考虑这个问题,我认为可以在 O(lg n) 时间内使用 O(lg n) 内存使用来完成此操作。这是基于
F(n) = (1 / √5) (Φn - φn)
其中 Φ = (1 + √5)/2且 φ = 1 - Φ。
第一个观察结果是 φn < 1 对于任意 n > 1 1. 这意味着对于任何 n > 2、我们有
F(n) = ⌊ Φn / √5 ⌋
现在,将 n 写成二进制 bk-1bk -2...b1b0。这意味着
n = 2k-1 bk-1 + 2k-2 bk-2 + ... + 21 b1 + 20 b0。
这意味着
F(n) = ⌊ Φ2k-1 bk-1 + 2k-2 bk-2 + ... + 21 b1 + 20 b0 / √5 ⌋
或者,更易读的是,
F(n) = ⌊ Φ2k-1 bk-1 Φ2k-2 bk-2 ... Φ21 b 1Φ20 b0 / √5 ⌋
这表明了以下算法。首先,开始计算所有 k 的 Φ2k,直到计算出一个数字 Φz,使得 ⌊ Φz / √5 ⌋ 大于您的数字 F(n)。现在,从那里开始向后迭代以这种方式生成的 Φ 的所有幂。如果当前数字大于指示的 Φ 次方,则将其除以 Φ 次方,并记录该数字除以该值。这个过程本质上是通过一次减去 2 的最大幂来一次恢复 n 的一位。因此,一旦完成,您就会找到n。
该算法的运行时间为 O(lg n),因为您可以通过重复平方生成 Φ2i,而我们只生成 O(lg n) 项。内存使用量为 O(lg n),因为我们存储所有这些值。
So I was thinking about this problem and I think that it's possible to do this in O(lg n) time with O(lg n) memory usage. This is based on the fact that
F(n) = (1 / √5) (Φn - φn)
Where Φ = (1 + √5)/2 and φ = 1 - Φ.
The first observation is that φn < 1 for any n > 1. This means that for any n > 2, we have that
F(n) = ⌊ Φn / √5 ⌋
Now, take n and write it in binary as bk-1bk-2...b1b0. This means that
n = 2k-1 bk-1 + 2k-2 bk-2 + ... + 21 b1 + 20 b0.
This means that
F(n) = ⌊ Φ2k-1 bk-1 + 2k-2 bk-2 + ... + 21 b1 + 20 b0 / √5 ⌋
Or, more readably, that
F(n) = ⌊ Φ2k-1 bk-1Φ2k-2 bk-2 ... Φ21 b1Φ20 b0 / √5 ⌋
This suggests the following algorithm. First, start computing Φ2k for all k until you compute a number Φz such that ⌊ Φz / √5 ⌋ that's greater than your number F(n). Now, from there, iterate backwards across all of the powers of Φ you generated this way. If the current number is bigger than the indicated power of Φ, then divide it by that power of Φ and record that the number was divided by this value. This process essentially recovers one bit of n at a time by subtracting out the largest power of 2 that you can at a time. Consequently, once you're done, you'll have found n.
The runtime of this algorithm is O(lg n), since you can generate Φ2i by repeated squaring, and we only generate O(lg n) terms. The memory usage is O(lg n), since we store all of these values.
您可以在 O(1) 时间和 O(1) 空间中找到任意 Fib(n) 的 n。
您可以使用定点 CORDIC 算法仅使用整数数据类型的移位和加法来计算 ln()。
如果 x = Fib(n),则 n 可以通过 CORDIC 确定,
运行时间由所需的精度水平确定。这两个浮点值将被编码为定点值。
该提案的唯一问题是,它返回一个不在斐波那契数列中的数字值,但最初的问题明确指出该函数的输入将为 Fib(n),这意味着只有有效的斐波那契数才是用过的。
You can find n for any Fib(n) in O(1) time and O(1) space.
You can use a fixed-point CORDIC algorithm to compute ln() using only shift and add on integer data types.
If x = Fib(n), then n can be determined by
CORDIC run-time is determined by the desired level of precision. The two floating-point values would be encoded as fixed-point values.
The only issue with this proposal is that it returns a value for numbers that are not in the Fibonacci sequence, but the original problem specifically stated that the input to the function would be Fib(n), which implies that only valid Fibonacci numbers would be used.
编辑:没关系。提问者在评论中指出,求幂绝对不是常数时间。
求幂是您在恒定时间内允许的数学运算之一吗?如果是这样,我们可以通过 封闭式公式 在恒定时间内计算 F(n) 。然后,给定一些 F,我们可以执行以下操作:
如果 F = F(n),则第一部分需要 k = O(log(n)) 步骤。第二部分是在大小为 O(2^k) 的范围内进行二分搜索,因此它也需要 k = O(log(n))。因此,总的来说,我们在 O(1) 空间中拥有 O(log(n)) 时间如果(这是一个很大的假设)我们在 O(1) 时间内求幂。
EDIT: Never mind. The asker has stated in comments that exponentiation is definitely not constant time.
Is exponentiation one of the mathematical operations that you'll allow in constant time? If so, we can compute F(n) in constant time via the closed-form formula. Then, given some F, we can do the following:
If F = F(n), then first part takes k = O(log(n)) steps. The second part is a binary search over a range of size O(2^k), so it also takes k = O(log(n)). So, in total, we have O(log(n)) time in O(1) space if (and it's a big if) we have exponentiation in O(1) time.
斐波那契数列公式的封闭形式为:
其中 φ 是黄金比例。
如果我们忽略舍入因子,则这是可逆的,其反函数为:
因为我们忽略了舍入因子,所以计算公式中存在错误。然而,如果我们认为数字 n 是斐波那契数,当且仅当区间 [n*φ - 1/n, n*φ + 1/n] 包含自然数时:
一个数是斐波那契数,当且仅当区间 [n* φ - 1/n, n*φ + 1/n] 包含一个自然数,该数字在斐波那契序列中的索引由舍入 log(n*Sqrt(5))/logφ 给出,
这应该可以在(伪)-常数时间取决于用于计算对数和平方根等的算法。
编辑: φ = (1+Sqrt(5))/2
A closed form of the Fibonacci number formula is:
Where φ is the golden ratio.
If we ignore the rounding factor this is invertible and the inverse function is:
Because we ignored the rounding factor there is an error in the formula which could be calculated. However if we consider that a number n is a Fibonacci number iff the interval [n*φ - 1/n, n*φ + 1/n] contains a natural number then:
A number is a Fibonacci number iff the interval [n*φ - 1/n, n*φ + 1/n] contains a natural number and that number's index in the Fibonacci sequence is given by rounding log(n*Sqrt(5))/logφ
This should be doable in (pseudo)-constant time depending on the algorithms used for calculating the log and square roots etc.
Edit: φ = (1+Sqrt(5))/2
这可能与 user635541 的答案类似。我不完全理解他的做法。
使用其他答案中讨论的斐波那契数的矩阵表示,我们得到了从
F_n
和F_m
到F_{n+m}
的方法> 和F_{nm}
在常数时间内仅使用加、乘、减和除(实际上不是!请参阅更新)。我们还有一个零(单位矩阵),所以它是一个数学群!通常在进行二分搜索时,我们还需要一个除法运算符来取平均值。或者至少除以 2。但是,如果我们想从
F_{2n}
到F_n
,则需要平方根。幸运的是,事实证明,加号和减号就是我们“接近”二分搜索所需的对数时间!维基百科写了有关该方法的文章,讽刺的是称为 Fibonacci_search,但文章写得不是很清楚,所以我不知道和我的做法是不是一模一样。理解用于斐波那契搜索的斐波那契数与我们正在寻找的数无关是非常重要的。这有点令人困惑。为了演示该方法,这里首先是仅使用加号和减号的标准“二分搜索”的实现:
这里
test
是一些布尔函数;a
和b
是连续的斐波那契数f_k
和f_{k-1}
,这样上层之间的差异上界hi
和下界lo
始终为f_k
。我们需要a
和b
,这样我们就可以有效地增加和减少隐式变量k
。好吧,那么我们如何使用它来解决这个问题呢?我发现围绕斐波那契表示创建一个包装器很有用,它隐藏了矩阵细节。在实践中(斐波那契搜索器有这样的事情吗?)您可能希望手动内联所有内容。这将为您节省矩阵中的冗余,并围绕矩阵求逆进行一些优化。
然而代码确实有效,所以我们可以按如下方式测试它。请注意,当我们的对象是整数而不是斐波那契时,搜索函数几乎没有什么不同。
剩下的悬而未决的问题是是否存在一种有效的幺半群搜索算法。这是不需要减/加逆的。我的猜测是否定的:如果没有负号,您需要 Nikita Rybak 的额外内存。
更新
我刚刚意识到我们根本不需要分裂。
F_n
矩阵的行列式就是(-1)^n
,所以我们实际上可以做任何事情而无需除法。在下面,我删除了所有矩阵代码,但保留了 Fib 类,因为否则一切都会变得非常混乱。这一切就像一个魅力。我唯一担心的是位复杂性在计算中占主导地位,我们可能只是进行了顺序搜索。或者实际上,仅查看位数就可以告诉您所查看的内容。但这并不那么有趣。
This might be similar to user635541's answer. I don't fully understand his approach.
Using the matrix representation for Fibonacci numbers, discussed in other answers, we get a way to go from
F_n
andF_m
toF_{n+m}
andF_{n-m}
in constant time, using only plus, multiplication, minus and division (actually not! see the update). We also have a zero (the identity matrix), so it is a mathematical group!Normally when doing binary search we also want a division operator for taking averages. Or at least division by 2. However if we want to go from
F_{2n}
toF_n
it requires a square root. Luckily it turns out that plus and minus are all we need for a logarithmic time 'nearly' binary search!Wikipedia writes about the approach, ironically called Fibonacci_search, but the article is not very clearly written, so I don't know if it is exactly the same approach as mine. It is very important to understand that the Fibonacci numbers used for the Fibonacci search have nothing to do with the numbers we are looking for. It's a bit confusing. To demonstrate the approach, here is first an implementation of standard 'binary search' only using plus and minus:
Here
test
is some boolean function;a
andb
are consecutive fibonacci numbersf_k
andf_{k-1}
such that the difference between out upper boundhi
and lower boundlo
is alwaysf_k
. We need botha
andb
so we can increase and decrease the implicit variablek
efficiently.Alright, so how do we use this to solve the problem? I found it useful to create a wrapper around our Fibonacci representation, that hides the matrix details. In practice (is there such a thing for a Fibonacci searcher?) you would want to inline everything manually. That would spare you the redundancy in the matrices and make some optimization around the matrix inversion.
However the code does work, so we can test it as follows. Notice how little different the search function is from when our objects were integers and not Fibonaccis.
The remaining open question is whether there is an efficient search algorithm for monoids. That is one that doesn't need a minus / additive inverse. My guess is no: that without minus you need the extra memory of Nikita Rybak.
Update
I just realized that we don't need division at all. The determinant of the
F_n
matrix is just(-1)^n
, so we can actually do everything without division. In the below I removed all the matrix code, but I kept theFib
class, just because everything got so extremely messy otherwise.This all works like a charm. My only worry is that the bit complexity such dominates the calculation, that we might as well have just done a sequential search. Or actually, just looking at the number of digits could probably tell you pretty much which you were looking at. That's not as fun though.