【发布时间】:2015-12-06 02:48:27
【问题描述】:
我需要做一个快速算法(我已经做了一个慢算法),它将从两个整数范围(范围可以相交或不相交)中找到所有可能值的数量,总和将是给定的数字
我可以将其表示为等式:z = x + y
其中 z 是一个已知数,等于 x 加上 y
z 可以是 0 到10^18
x 属于整数范围 [a..b],其中 0 连续数字之间的差是1
y 属于整数范围 [c..d],其中 0 连续数字之间的差是1
所以我需要从总和为 z 的两组数字中找到 x 和 y 的所有可能变化的数字(不是它们的确切值)
示例:
z = 5
第一组:a = 1, b = 5(表示该组由1,2,3,4,5组成)
第二组:c = 1,b = 5
那么答案是 4,因为所有可能的组合都是:
x = 4, y = 1
x = 3, y = 2
x = 2, y = 3
x = 1, y = 4
因为他们的总和是 5
算法的强制条件是工作速度超过 1 秒
以下代码可以正常工作,但仅适用于小于 1000000 的数字。对于大数字,它的工作速度要慢得多
with open(r"input.txt") as f:
n = int(f.readline()) # the given number
a = int(f.readline()) # the start position of the first set
b = int(f.readline()) # the end position of the first set
c = int(f.readline()) # the start position of the second set
d = int(f.readline()) # the end position of the second set
# print "n:",n,"a:",a,"b:",b,"c:",c,"d:",d
t = b - a + 1 # all posible variants of the first set
k = d - c + 1 # all posible variants of the second set
number_of_vars = 0
if t >= k:
while b >= a:
if (n - b <= d) \
and (n - b>= c):
number_of_vars += 1
b -= 1
else:
b -= 1
if t < k:
while d >= c:
if (n-d <= b) and (n-d >= a):
number_of_vars += 1
d -= 1
else:
d -= 1
print number_of_vars
【问题讨论】: