The following Julua code is much slower than Ruby and Python because of the slow way it removes the members of one array from another.
function prime_pairs_lohi(n)
if (n&1 == 1 || n < 4) return println("Input not even n > 2") end
if (n <= 6) println([n, 1]); println([div(n,2),div(n,2)]); println([div(n,2),div(n,2)]); return end
# generate the low-half-residues (lhr) r < n/2
ndiv2, rhi = div(n,2), n-2 # lhr:hhr midpoint, max residue limit
lhr = [] # array for low half residues
for r in 3:2:ndiv2; if (gcd(r, n) == 1) append!(lhr, r) end end
# store all powers and cross-products of the lhr members < n-2
lhr_mults = [] # lhr multiples, not part of a pcp
i = 2; ln = length(lhr)
while (i < ln)
r = lhr[i-1] # make 1st lhr reference multiplier
rmax = div(rhi, r) # ri can't multiply r with values > this
if (r < rmax) append!(lhr_mults, r*r) end # for r^2 multiples
if (lhr[i] > rmax) break end # exit if product of consecutive r’s > n-2
j = i # index to next larger residue in lhr
while (j < ln) # for each residue in reduced list
if (lhr[j] > rmax) break end # exit for r if cross-product with ri > n-2
append!(lhr_mults, r * lhr[j]) # store value if < n-2
j += 1 # next lhr value to multiply
end
i += 1
end
# convert lhr_mults vals > n/2 to their lhr complements n-r,
# store them, those < n/2, in lhr_del; it now holds non-pcp lhr vals
lhr_del = []
for r in lhr_mults # convert all lhr multiples to lhr values
r_del = (r > ndiv2) ? n - r : r # convert r > n/2 to lhr mc if necessary
append!(lhr_del, r_del) # store in lhr_del
end
lhr = setdiff(lhr,lhr_del) # remove lhr_del multiples from lhr
println([n, length(lhr)]) # show n and pcp prime pairs count
println([first(lhr),n-first(lhr)]) # show first pcp prime pair of n
println([last(lhr), n-last(lhr)]) # show last pcp prime pair of n
end
num = readline() # get n value string from terminal
n = parse(Int64, num) # convert to Int64 integer value
@time begin prime_pairs_lohi(n) end # execute code and show its timing
In Ruby|Crystal its: lhr -= lhr_del
In Pyrhon its: lhr = [r for r in lhr if r not in lhr_del]
In Julia this is mag orders slower: lhr = setdiff(lhr,lhr_del)
Is there a way to do this faster, and in general, to optimize all the code.