Middle Earth

python 有这么慢吗

逻辑几乎相同的两段代码,python 比 C 慢 50 倍?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* Find the sum of all numbers which are equal to the sum of the factorial of
   their digits. */

#include <stdio.h>

int solve()
{
    int f[10];
    int i, limit, sum;

    f[0] = 1;
    for (i=1; i<10; i++)
        f[i] = f[i-1]*i;
    limit = 7*f[9];
    sum = 0;
    for (i=3; i<=limit; i++) {
        int s = 0;
        int j = i;
        while (j>0) {
            s += f[j%10];
            j /= 10;
        }
        if (i==s)
            sum += i;
    }
    return sum;
}

int main()
{
    printf("%d\n", solve());
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Find the sum of all numbers which are equal to the sum of the factorial of
# their digits.

import math

def solve():
    f = [math.factorial(i) for i in range(10)]
    limit = 7*f[9]
    ret = []
    for i in range(3, limit+1):
        s = 0
        j = i
        while j>0:
            s += f[j%10]
            j /= 10
        if i==s:
            ret.append(i)
    return ret

print sum(solve())
1
2
3
4
5
6
7
8
9
10
11
12
13
$ time python 34-sum-of-digit-factorial.py
40730

real    0m5.053s
user    0m4.850s
sys     0m0.145s

$ time ./a.out
40730

real    0m0.115s
user    0m0.111s
sys     0m0.002s

这是 Project Euler 的第 34 题。

Comments