The Julia code on this page is much slower than the Python examples.
Euler’s sum of powers conjecture with code examples
I wrote a Julia program similar to the fastest Python example:
Julia
function main()
MAX = 250
p5 = Dict()
sum2 = Dict()
sk = []
for i in range(1, MAX)
p5[i^5] = i
for j in range(i, MAX)
sum2[i^5 + j^5] = (i, j)
end
end
sk = sort(collect(keys(sum2)))
for p in sort(collect(keys(p5)))
for s in sk
if p <= s ; break ; end
if p - s in keys(sum2)
println(p5[p], sum2[s], sum2[p-s])
# exit()
end
end
end
end
main()
~]$ time julia euler2.jl
144(27, 84)(110, 133)
144(27, 110)(84, 133)
144(84, 110)(27, 133)
144(27, 133)(84, 110)
144(84, 133)(27, 110)
144(110, 133)(27, 84)
real 0m0.996s
user 0m0.982s
sys 0m0.222s
Python
MAX = 250
p5, sum2 = {}, {}
sk = []
for i in range(1, MAX):
p5[i**5] = i
for j in range(i, MAX):
sum2[i**5 + j**5] = (i, j)
sk = sorted(sum2.keys())
for p in sorted(p5.keys()):
for s in sk:
if p <= s: break
if p - s in sum2:
print(p5[p], sum2[s] + sum2[p-s])
# exit()
]$ time python euler2.py
144 (27, 84, 110, 133)
144 (27, 110, 84, 133)
144 (84, 110, 27, 133)
144 (27, 133, 84, 110)
144 (84, 133, 27, 110)
144 (110, 133, 27, 84)
real 0m0.559s
user 0m0.546s
sys 0m0.009s
I was surprised that the speed of these basic loop algorithm differed by almost a factor of two.
The Python can also be made faster by putting the nested loop into a method, like so:
MAX = 250
p5, sum2 = {}, {}
sk = {}
for i in range(1, MAX):
p5[i**5] = i
for j in range(i, MAX):
sum2[i**5 + j**5] = (i, j)
sk = sorted(sum2.keys())
def methodC ():
for p in sorted(p5.keys()):
for s in sk:
if p <= s: break
if p - s in sum2:
yield p5[p], sum2[s] + sum2[p-s]
for v1, v2 in methodC ():
print (v1, v2)
~]$ time python euler3.py
144 (27, 84, 110, 133)
144 (27, 110, 84, 133)
144 (84, 110, 27, 133)
144 (27, 133, 84, 110)
144 (84, 133, 27, 110)
144 (110, 133, 27, 84)
real 0m0.368s
user 0m0.351s
sys 0m0.014s
Does anyone have any suggestions on how to optimize this Julia program to make it faster?