【发布时间】:2013-12-01 15:55:49
【问题描述】:
我正在做项目 euler Q14。
100 万以下的哪个起始数字产生最长的 collatz 链?
看到有人能在 0.7 秒内得到结果,我感到非常惊讶。当我看到它只是一个幼稚的蛮力解决方案时,我更加惊讶。
我很怀疑,因为我花了很多时间来优化我的 python 版本,将运行时间缩短到大约一分钟。所以我自己运行代码...... OP 没有撒谎。
我将相同的代码翻译成 Python,5 分钟后无法终止。
什么给了?
C 版:http://codepad.org/VD9QJDkt
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
int longest = 0;
int terms = 0;
int i;
unsigned long j;
clock_t begin, end;
double time_spent;
begin = clock();
for (i = 1; i <= 1000000; i++)
{
j = i;
int this_terms = 1;
while (j != 1)
{
this_terms++;
if (this_terms > terms)
{
terms = this_terms;
longest = i;
}
if (j % 2 == 0)
{
j = j / 2;
}
else
{
j = 3 * j + 1;
}
}
}
printf("longest: %d (%d)\n", longest, terms);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("It took %f seconds\n", time_spent);
return 0;
}
Python 版本:http://codepad.org/ZloPyEcz
import time
def iterative_brute_force(n):
longest = 0
terms = 0
for i in range(1, n + 1):
j = i
this_terms = 1
while j != 1:
this_terms += 1
if this_terms > terms:
terms = this_terms
longest = i
if j % 2 == 0:
j = j / 2
else:
j = 3 * j + 1
return longest, terms
t0 = time.time()
print(iterative_brute_force(10 ** 6))
t1 = time.time()
total = t1-t0
print(total)
【问题讨论】:
-
你认为 python 比 c 运行得更快吗?另外,我认为问题出在您的python算法中..
-
你应该看到this
-
@aIKid 我不认为令人惊讶的是它更慢,但它需要 这么多(至少 300 倍)更多时间。两个程序的算法相同,所以这不是问题。
-
我不是专家,但您确定您的 while 循环符合您的预期吗?
-
@Leeor 你发现了。现在将其扩展为一个答案,并点赞:-)
标签: python c performance code-translation