Hello, I just started learning Erlang and have already encountered performance disappointment when calculating math. Unfortunately, I don’t see ways to improve performance, and my hands have already dropped.
Such code:
% делится ли N на какое-нибудь число из списка % [] - делится, [N] - не делится del(N, [H|_]) when N rem H=:=0 -> []; del(N, [_|T]) -> del(N, T); del(N, []) -> [N]. % список простых чисел от 2 до N prosto(N) when is_integer(N), N>1 -> prosto(N, [], 2). prosto(N, Acc, St) when N+1=:=St -> lists:reverse(Acc); prosto(N, Acc, St) ->prosto(N, del(St, Acc)++Acc, St+1).
When creating a list of up to 200,000, it takes an average of 39 seconds.
Java similar functionality code
static boolean del(int N, ArrayList<Integer> L){ int size=L.size(); for (int i=0; i<size; i++) { if (N % L.get(i)==0) return true; } return false; } static ArrayList<Integer> prosto(int N){ ArrayList<Integer> res=new ArrayList<Integer>(); for (int i=2; i<=N; i++) { if (!del(i, res)) res.add(i); } return res; }
When creating a list of the same length, it takes an average of 0.75 seconds. 52 times faster.
Question : Is it possible to create more efficient code on erlang?
del(St, Acc)++Acc
looks suspicious.[hd(del(St, Acc)]|Acc]
or[St|Acc]
may be better. - alexlz