public
Last active

Python vs. PyPy vs. Julia comparison - Factorials & Looping

  • Download Gist
python-pypy-julia.py
Python
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#Python/pypy
import math
def smallestdivisall(n):
for i in xrange(1, math.factorial(n)+1):
for j in xrange(1, n+1):
if i % j != 0:
break
elif j == n:
return i
 
#IPython timer
In [1]: %time smallestdivisall(20)
#Python w/ Numba @autojit
import math
from numba import autojit
 
@autojit
def smallestdivisall(n):
for i in xrange(1, math.factorial(n)+1):
for j in xrange(1, n+1):
if i % j != 0:
break
elif j == n:
return i
 
#IPython timer
In [1]: %time smallestdivisall(20)
 
#Julia, 2nd run to remove compilation time
function smallestdivisall(n::Int64)
for i = 1:factorial(n)
for j = 1:n
if i % j !=0
break
elseif j == n
return i
end
end
end
end
 
#Julia time macro
julia> @time smallestdivisall(20)
 
#R
smallestdivisall <- function(n){
require("iterators") #Need because large values for n don't fit in vector, so use iterator
m <- icount(factorial(n))
i <- nextElem(m)
while(i < factorial(n)) {
for (j in 1:n) {
if (i %% j != 0) {
break
} else if (j == n) {
return(i)
}
}
i <- nextElem(m)
}
}
 
#R timer
system.time(smallestdivisall(20))
 
 
#Compile function to see speed up
library(compiler)
enableJIT(1)
smallestdivisall_c <- cmpfun(smallestdivisall)
 
#R timer
system.time(smallestdivisall_c(20))

What values of n are you using in the Julia code? factorial(n) overflows very quickly.

The Julia function is only valid at n < 21 to avoid overflow, which is why my graphs are from 4 < n < 21

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.