我试图用 Python编写问题 12(Project Euler)的解决方案。解决方案太慢了,所以我尝试在互联网上检查其他人的解决方案。我发现这段代码是用 C++ 编写的,它与我的 python 代码几乎完全相同,只有一些微不足道的差异。
Python:
def find_number_of_divisiors(n):
if n == 1:
return 1
div = 2 # 1 and the number itself
for i in range(2, n/2 + 1):
if (n % i) == 0:
div += 1
return div
def tri_nums():
n = 1
t = 1
while 1:
yield t
n += 1
t += n
t = tri_nums()
m = 0
for n in t:
d = find_number_of_divisiors(n)
if m < d:
print n, ' has ', d, ' divisors.'
m = d
if m == 320:
exit(0)
C++:
#include <iostream>
int main(int argc, char *argv[])
{
unsigned int iteration = 1;
unsigned int triangle_number = 0;
unsigned int divisor_count = 0;
unsigned int current_max_divisor_count = 0;
while (true) {
triangle_number += iteration;
divisor_count = 0;
for (int x = 2; x <= triangle_number / 2; x ++) {
if (triangle_number % x == 0) {
divisor_count++;
}
}
if (divisor_count > current_max_divisor_count) {
current_max_divisor_count = divisor_count;
std::cout << triangle_number << " has " << divisor_count
<< " divisors." << std::endl;
}
if (divisor_count == 318) {
exit(0);
}
iteration++;
}
return 0;
}
python 代码在我的机器上执行需要 1 分 25.83 秒。而 C++ 代码大约需要 4.628 秒。它的速度快了 18 倍。我曾预计 C++ 代码会更快,但不会有这么大的优势,而且这也只是一个简单的解决方案,它只包含 2 个循环和一堆增量和模块。
虽然我很想知道如何解决这个问题的答案,但我想问的主要问题是为什么 C++ 代码这么快?我在 python 中使用/做错了什么吗?
用 xrange 替换范围:
用 xrange 替换 range 后,python 代码大约需要 1 分 11.48 秒才能执行。(大约快 1.2 倍)