反向Collat​​z猜想

时间:2018-07-26 11:39:30

标签: python collatz

程序应该做的是采取步骤和一个数字,然后输出给您多少个唯一的序列,它们精确地x为steps来创建number

有人知道我可以如何节省一些内存-因为我应该在4秒内使这项工作适用于非常庞大的数字。

def IsaacRule(steps, number):
    if number in IsaacRule.numbers:
        return 0
    else:
        IsaacRule.numbers.add(number)
    if steps == 0:
        return 1
    counter = 0
    if ((number - 1) / 3) % 2 == 1:
        counter += IsaacRule(steps-1, (number - 1) / 3)
    if (number * 2) % 2 == 0:
        counter += IsaacRule(steps-1, number*2)

    return counter

IsaacRule.numbers = set()

print(IsaacRule(6, 2))

如果有人知道带有备忘的版本,我会很感激,现在可以使用,但是仍有改进的空间。

1 个答案:

答案 0 :(得分:0)

基线:IsaacRule(50, 2)花费6.96秒

0)使用LRU缓存

这使代码花费了更长的时间,并给出了不同的最终结果

1)消除if条件:(number * 2) % 2 == 0True

IsaacRule(50, 2)耗时0.679s。感谢Pm2Ring。

2)将((number - 1) / 3) % 2 == 1简化为number % 6 == 4,并在可能的情况下使用楼层分割:

IsaacRule(50, 2)耗时0.499s

真值表:

| n | n-1 | (n-1)/3 | (n-1)/3 % 2 | ((n-1)/3)%2 == 1 |
|---|-----|---------|-------------|------------------|
| 1 | 0   | 0.00    | 0.00        | FALSE            |
| 2 | 1   | 0.33    | 0.33        | FALSE            |
| 3 | 2   | 0.67    | 0.67        | FALSE            |
| 4 | 3   | 1.00    | 1.00        | TRUE             |
| 5 | 4   | 1.33    | 1.33        | FALSE            |
| 6 | 5   | 1.67    | 1.67        | FALSE            |
| 7 | 6   | 2.00    | 0.00        | FALSE            |

代码:

def IsaacRule(steps, number):
    if number in IsaacRule.numbers:
        return 0
    else:
        IsaacRule.numbers.add(number)
    if steps == 0:
        return 1
    counter = 0
    if number % 6 == 4:
        counter += IsaacRule(steps-1, (number - 1) // 3)
    counter += IsaacRule(steps-1, number*2)

    return counter

3)使用集合重写代码

IsaacRule(50, 2)耗时0.381s

这使我们可以利用对集合所做的任何优化。基本上,我在这里进行广度优先搜索。

4)中断循环,以便我们跳过对先前状态的跟踪。

IsaacRule(50, 2)耗时0.256s

我们只需要添加一个检查number != 1即可打破唯一已知的周期。这样可以加快速度,但是如果您从1开始,则需要添加一个特殊情况。谢谢Paul的建议!

START = 2
STEPS = 50

# Special case since we broke the cycle
if START == 1:
    START = 2
    STEPS -= 1

current_candidates = {START} # set of states that can be reached in `step` steps

for step in range(STEPS):
    # Get all states that can be reached from current_candidates
    next_candidates = set(number * 2 for number in current_candidates if number != 1) | set((number - 1) // 3 for number in current_candidates if number % 6 == 4)

    # Next step of BFS
    current_candidates = next_candidates
print(len(next_candidates))