仍然存在的问题:
当 n 不同时,输出结果不同,例如 n=1000和n=10000时,目前并不太确定这是为什么?
方法
首先我们可以想到最简单的方法就是暴力搜索,三次遍历,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from math import cos import time import numpy as np
defcalc(n): total = 0 for x in range(n): for y in range(n): for z in range(n): if x + y + z == n: temp = cos(x) + cos(y) + cos(z) if temp > total: total = temp return total
tic = time.clock() total = calc(1000) print(time.clock()-tic)
print (total)
73.1499421
2.843394328325828
因为速度非常慢,这里只用了1000来演示,之后使用10000来演示
这样的情况下,时间复杂度为O(N3)
也能很容易的想到将其改为两次循环,代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
from math import cos import time import numpy as np
defcalc(n): total = 0 for x in range(n): for y in range(n): z = n-x-y temp = cos(x) + cos(y) + cos(z) if temp > total: total = temp return total
tic = time.clock() total = calc(10000) print(time.clock()-tic)
from math import cos import time import numpy as np
defcalc(n): total = 0 for x in range(n, int((n/3 - 1)),-1): for y in range(max(int(((n-x)/2))-1,1),min(int(n-x),int(n/3))): z = n-x-y temp = cos(x) + cos(y) + cos(z) if temp > total: total = temp return total
tic = time.clock() total = calc(10000) print(time.clock()-tic)
from math import cos import time import numpy as np from numba import jit
@jit(nopython=True) defcalc(n): total = 0 for x in range(n, int((n/3 - 1)),-1): for y in range(max(int(((n-x)/2))-1,1),min(int(n-x),int(n/3))): z = n-x-y temp = cos(x) + cos(y) + cos(z) if temp > total: total = temp return total
tic = time.clock() total = calc(10000) print(time.clock()-tic)