科拉茨猜想相关采访
这是一个面试问题,似乎与欧拉项目 问题 14 有关,
Collatz 猜想说,如果您执行以下操作
If n is even, replace n by n/2.
If n is odd, replace n by 3n+1.
你最终会得到 1。
例如,5 -> 16-> 8-> 4-> 2-> 1
假设猜想成立,每个数字都有一个链长:到达1所需的步数。(1的链长为0)。
现在,问题给定自然数 n、m 和一个自然数 k,给出一个算法来查找 1 和 n 之间的所有数字,使得这些数字的链长度 <= k。还有一个限制,即任何这些数字的链必须仅包含 1 到 m 之间的数字(即不能超过 m)。
一个简单的方法是暴力破解它,并将其与记忆结合起来。
面试官说有一个O(S)时间的算法,其中S是我们需要输出的数字个数。
有谁知道它可能是什么?
This was an interview question, which seems related to Project Euler Problem 14
Collatz conjecture says that if you do the following
If n is even, replace n by n/2.
If n is odd, replace n by 3n+1.
You ultimately end up with 1.
For instance, 5 -> 16 -> 8 -> 4 -> 2 -> 1
Assuming the conjecture is true, each number has a chain length: The number of steps required to get to 1. (The chain length of 1 is 0).
Now, the problem is given natural numbers n, m and a natural number k, give an algorithm to find all numbers between 1 and n, such that the chain length of those numbers is <= k. There is also the restriction that the chain of any of those numbers must only include numbers between 1 and m (i.e. you cannot go over m).
An easy way is to brute-force it out, and combine that with memoization.
The interviewer said there was an O(S) time algorithm, where S is the number of numbers we need to output.
Does anyone know what it could be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你可以通过向后运行该过程来在 O(S) 中解决这个问题。如果您知道 k 是什么,那么您可以使用以下逻辑构建最多停止在 k 步中的所有数字:
由此,您可以开始构建从 1 开始的序列中的数字:
我们可以使用存储我们需要访问的数字及其长度的工作队列来执行此算法链。我们用 (1, 0) 填充队列,然后连续将一个元素 (z, n) 从队列中出列,并将 (2z, n + 1) 和(可能) ((z - 1) / 3, n + 入队1)进入队列。这本质上是在 Collatz 图中从一个开始进行广度优先搜索。当我们找到深度 k 处的第一个元素时,我们停止搜索。
假设科拉茨猜想成立,我们永远不会以这种方式得到任何重复项。此外,我们将通过这种方式找到最多 k 步可达的所有数字(您可以通过快速归纳证明来快速检查这一点)。最后,这需要 O(S) 时间。要看到这一点,请注意生成的每个数字完成的工作是一个常量(出队并向队列中插入最多两个新数字)。
希望这有帮助!
I think you can solve this in O(S) by running the process backwards. If you know what k is, then you can build up all of the numbers that halt in at most k steps using the following logic:
From this, you can start building up the numbers in the sequence starting at 1:
We could do this algorithm using a work queue storing numbers we need to visit and the lengths of their chains. We populate the queue with the pair (1, 0), then continuously dequeue an element (z, n) from the queue and enqueue (2z, n + 1) and (possibly) ((z - 1) / 3, n + 1) into the queue. This is essentially doing a breadth-first search in the Collatz graph starting from one. When we find the first element at depth k, we stop the search.
Assuming that the Collatz conjecture holds true, we'll never get any duplicates this way. Moreover, we'll have found all numbers reachable in at most k steps this way (you can quickly check this with a quick inductive proof). And finally, this takes O(S) time. To see this, note that the work done per number generated is a constant (dequeue and insert up to two new numbers into the queue).
Hope this helps!