我正在尝试使用 Python 解决 TalentBuddy 中的问题
问题是 :
给定一个数字 N。将可以使用 {1,2..N} 集合形成的子集的总数打印到标准输出,但要确保没有一个子集包含任何两个连续的整数。最终计数可能非常大,这就是为什么您必须以 524287 为模打印结果。
我已经处理了代码。除测试 6 外,所有测试都正常。当测试作为函数的参数OverFlowError
提交时,我得到了。10000000
我不知道我应该怎么做才能解决这个错误
我的代码:
import math
def count_subsets(n):
step1 = (1 / math.sqrt(5)) * (((1 + math.sqrt(5)) / 2) ** (n + 2))
step2 = (1 / math.sqrt(5)) * (((1 - math.sqrt(5)) / 2) ** (n + 2))
res = step1 - step2
print int(res) % 524287
我想这会占用很多内存。我在互联网上找到了同一主题的数学公式后写了这篇文章。
我想我的代码根本不是 Pythonic。
如何做到这一点,“Pythonic”方式?如何解决OverFlowError
?
编辑:在问题中,我给出了示例 input 3
,结果(输出)是5
.
解释: 5 组是,{}, {1}, {2}, {3}, {1,3}
。
但是,在测试 6 中,我给出的问题是:
测试 #6 总结
输入测试:
[10000000]
预期输出:
165366
你的输出:
Traceback (most recent call last):
On line 4, in function count_subsets:
step1 = (1 / math.sqrt(5)) * (((1 + math.sqrt(5)) / 2) ** (n + 2))
OverflowError: