草图:
按照@Steve 的建议,首先找出所有素数max(l1) + max(l2)。让我们将该列表称为primes。注意:primes 不需要是列表;您可以改为 generate primes up the max 一次一个。
交换您的列表(如有必要),使 l2 成为最长的列表。然后把它变成一个集合:l2 = set(l2)。
排序l1 (l1.sort())。
然后:
for p in primes:
for i in l1:
diff = p - i
if diff < 0:
# assuming there are no negative numbers in l2;
# since l1 is sorted, all diffs at and beyond this
# point will be negative
break
if diff in l2:
# print whatever you like
# at this point, p is a prime, and is the
# sum of diff (from l2) and i (from l1)
唉,如果l2 是,例如:
l2 = [2, 3, 100000000000000000000000000000000000000000000000000]
这是不切实际的。它依赖于这一点,就像在您的示例中一样,max(max(l1), max(l2)) 是“相当小的”。
充实
嗯!您在评论中说列表中的数字最长为 5 位。所以他们不到100,000。你在一开始就说这个列表每个有 50,000 个元素。所以它们每个都包含大约一半的小于 100,000 的所有可能整数,并且您将有大量的素数和。如果您想进行微优化,这一切都很重要 ;-)
无论如何,由于最大可能的总和小于 200,000,因此 任何 筛分方式都足够快 - 这将是运行时的一个微不足道的部分。以下是其余代码:
def primesum(xs, ys):
if len(xs) > len(ys):
xs, ys = ys, xs
# Now xs is the shorter list.
xs = sorted(xs) # don't mutate the input list
sum_limit = xs[-1] + max(ys) # largest possible sum
ys = set(ys) # make lookups fast
count = 0
for p in gen_primes_through(sum_limit):
for x in xs:
diff = p - x
if diff < 0:
# Since xs is sorted, all diffs at and
# beyond this point are negative too.
# Since ys contains no negative integers,
# no point continuing with this p.
break
if diff in ys:
#print("%s + %s = prime %s" % (x, diff, p))
count += 1
return count
我不会提供我的gen_primes_through(),因为这无关紧要。从其他答案中选择一个,或者自己写。
这是提供测试用例的便捷方式:
from random import sample
xs = sample(range(100000), 50000)
ys = sample(range(100000), 50000)
print(primesum(xs, ys))
注意:我使用的是 Python 3。如果您使用的是 Python 2,请使用 xrange() 而不是 range()。
在两次运行中,每次运行大约需要 3.5 分钟。这就是您一开始就要求的(“分钟而不是天”)。 Python 2 可能会更快。返回的计数是:
219,334,097
和
219,457,533
可能的总数当然是 50000**2 == 2,500,000,000。
关于时间
所有这里讨论的方法,包括您的原始方法,所花费的时间与两个列表长度的乘积成正比。所有的摆弄都是为了减少常数因子。与原来的相比,这是一个巨大的改进:
def primesum2(xs, ys):
sum_limit = max(xs) + max(ys) # largest possible sum
count = 0
primes = set(gen_primes_through(sum_limit))
for i in xs:
for j in ys:
if i+j in primes:
# print("%s + %s = prime %s" % (i, j, i+j))
count += 1
return count
也许你会更好地理解这一点。为什么会有很大的改进?因为它用极快的集合查找取代了昂贵的isprime(n) 函数。它仍然需要与len(xs) * len(ys) 成比例的时间,但是通过用非常便宜的操作替换非常昂贵的内循环操作,“比例常数”被削减了。
事实上,primesum2() 在很多情况下也比我的primesum() 快。是什么让primesum() 在您的特定情况中更快的是,只有大约 18,000 个质数小于 200,000。因此,迭代素数(如 primesum() 所做的那样)比迭代具有 50,000 个元素的列表要快得多。
针对此问题的“快速”通用函数需要根据输入选择不同的方法。