I wanted to try the Julia programming language, as I heard it is supposed to be faster than Python. I decided to try a dynamic program for Project Euler #14, as it dealt with a lot of computation (finding the longest Collatz sequence).
I wrote a program for it in Julia, and then decided to try to make an analogous program in Python, so see how fast each of them were. However, on my machine, the Python program runs in about 2 seconds, while the Julia one takes about 7. This surprised me, because as I said before Julia claims to be faster than Python, so I was wondering if there was anything inherent about the scripts that makes the Julia one so much slower. I attempted to have them both computed in the same way.
Here are the scripts, I would appreciate any insight!
Julia:
global max_val = 0
global max_item = 0
global d = Dict{Integer,Integer}()
function coll_length(n)
#println(n)
global max_val
global max_item
global d
if haskey(d,n)
return d[n]
end
if n==1
answer = 1
elseif n%2==1
answer = 1+coll_length(3n+1)
else
answer = 1+coll_length(n/2)
end
d[n]=answer
if max_val<answer
max_val=answer
max_item=n
end
return answer
end
for i = 1:1000000
coll_length(i)
end
println(max_item)
Python:
d = {}
max_val = 0
max_item = 0
def coll_length(n):
global d
global max_val
global max_item
if n in d:
return d[n]
if n==1:
answer= 1
elif n%2==0:
answer= 1+coll_length(n/2)
else:
answer= 1+coll_length(3*n+1)
d[n]=answer
if max_val<answer:
max_val=answer
max_item=n
return answer
for n in range(1,1000000+1):
coll_length(n)
print max_item