I wanted to try the Julia programming language since I heard that it should be faster than Python. I decided to try the dynamic program for Project Euler # 14 , as it concerned a large number of calculations (finding the longest sequence of Collatz).
I wrote a program for it in Julia, and then decided to try to make a similar program in Python, so see how fast each one is. However, on my machine, the Python program runs in about 2 seconds, while Julia takes about 7. This surprised me because, as I said, Julia claims to be faster than Python, so I was wondering if something that is inherent in the scripts that make Julia so slower. I tried to make them both work out the same way.
Here are the scenarios, I would appreciate any insight!
Julia:
global max_val = 0
global max_item = 0
global d = Dict{Integer,Integer}()
function coll_length(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
source
share