并发Prime发生器

时间:2008-09-18 03:19:21

标签: concurrency erlang primes

我正在通过projecteuler.net上的问题来学习如何在Erlang中编程,而我正在努力创建一个可以在不到一分钟内创建低于200万的所有素数的素数生成器。使用顺序样式,我已经编写了三种类型的生成器,包括Eratosthenes的Sieve,并且它们都没有表现得足够好。

我认为一个并发的Sieve会很好用,但我收到了不好的消息,我不知道为什么。有关我遇到问题的原因或如何正确编码的任何建议?

这是我的代码,注释掉的部分是我试图让事情并发的地方:

-module(primeserver).
-compile(export_all).

start() ->
    register(primes, spawn(fun() -> loop() end)).

is_prime(N) -> rpc({is_prime,N}).

rpc(Request) ->
    primes ! {self(), Request},
    receive
        {primes, Response} ->
            Response
    end.

loop() ->
    receive
        {From, {is_prime, N}} ->
            if
                N  From ! {primes, false};
                N =:= 2 -> From ! {primes, true};
                N rem 2 =:= 0 -> From ! {primes, false};
                true ->
                    Values = is_not_prime(N),
                    Val = not(lists:member(true, Values)),
                    From ! {primes, Val}
            end,
            loop()
    end.

for(N,N,_,F) -> [F(N)];
for(I,N,S,F) when I + S  [F(I)|for(I+S, N, S, F)];
for(I,N,S,F) when I + S =:= N -> [F(I)|for(I+S, N, S, F)];
for(I,N,S,F) when I + S > N -> [F(I)].

get_list(I, Limit) ->
    if
        I 
            [I*A || A 
            []
    end.

is_not_prime(N) ->
    for(3, N, 2, 
        fun(I) -> 
            List = get_list(I,trunc(N/I)),
            lists:member(N,lists:flatten(List))
        end
        ).

    %%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end),
    %%SeedList = [A || A  
    %%      lists:foreach(fun(X) ->
    %%              Pid ! {in_list, X} 
    %%                end, SeedList)
    %%        end, L).

%%wait(I,N) ->
%%  List = [I*A || A  lists:member(X,List)
%%  end.

10 个答案:

答案 0 :(得分:7)

我使用Go和渠道编写了一个Eratosthenesque并发主筛。

以下是代码:http://github.com/aht/gosieve

我在这里写了博客:http://blog.onideas.ws/eratosthenes.go

该程序可以在大约10秒钟内筛选出第一批百万个素数(所有素数达到15,485,863)。筛子是并发的,但算法主要是同步的:goroutines(“actor” - 如果你愿意)之间需要太多同步点,因此它们不能并行自由漫游。

答案 1 :(得分:3)

'badarity'错误意味着你试图用错误数量的参数调用'fun'。在这种情况下......

%% L = for(1,N,fun() - > spawn(fun(I) - > wait(I,N)end)end),

for / 3函数需要arity 1的乐趣,而spawn / 1函数需要一个arity 0的乐趣。试试这个:

L = for(1, N, fun(I) -> spawn(fun() -> wait(I, N) end) end),

传递给spawn的乐趣继承了其环境所需的部分(即I),因此不需要显式传递它。

虽然计算素数总是很有趣,但请记住,这不是Erlang旨在解决的问题。 Erlang是为大规模的演员风格并发而设计的。它很可能在数据并行计算的所有示例上表现得相当糟糕。在许多情况下,a sequential solution in, say, ML将会如此之快,以至于任何数量的内核都不足以让Erlang赶上来,例如对于这类行动来说,F# and the .NET Task Parallel Library肯定会是一个更好的工具。

答案 2 :(得分:1)

另一种考虑的替代方案是使用概率性素数生成。在乔的书(“主要服务器”)中有一个例子,它使用米勒 - 拉宾,我认为......

答案 3 :(得分:1)

您可以找到四种不同的Erlang实现来查找素数(其中两种基于Eratosthenes的Sieve)here。此链接还包含比较4种解决方案性能的图表。

答案 4 :(得分:0)

Eratosthenes的筛子相当容易实施,但是 - 正如您所发现的那样 - 并不是最有效的。你试过阿特金的筛子吗?

Sieve of Atkin @ Wikipedia

答案 5 :(得分:0)

答案 6 :(得分:0)

两个快速单进程erlang prime生成器; sprimes在~2.7秒内产生2m以下的所有质数,在我的计算机上产生〜3秒〜(带有2.4 GHz Core 2 Duo的Macbook)。两者都基于Eratosthenes的Sieve,但由于Erlang最适合使用列表而不是数组,因此它们都保留了一系列未消除的素数,检查当前头部的可分性并保留已验证质数的累加器。两者都实现了一个初始轮减少列表。

-module(primes).
-export([sprimes/1, wheel/3, fprimes/1, filter/2]).    

sieve([H|T], M) when H=< M -> [H|sieve([X || X<- T, X rem H /= 0], M)];
sieve(L, _) -> L.
sprimes(N) -> [2,3,5,7|sieve(wheel(11, [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10], N), math:sqrt(N))].

wheel([X|Xs], _Js, M) when X > M ->
    lists:reverse(Xs);
wheel([X|Xs], [J|Js], M) ->
    wheel([X+J,X|Xs], lazy:next(Js), M);
wheel(S, Js, M) ->
    wheel([S], lazy:lazy(Js), M).

fprimes(N) ->
    fprimes(wheel(11, [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10], N), [7,5,3,2], N).
fprimes([H|T], A, Max) when H*H =< Max ->
    fprimes(filter(H, T), [H|A], Max);
fprimes(L, A, _Max) -> lists:append(lists:reverse(A), L).

filter(N, L) ->
    filter(N, N*N, L, []).
filter(N, N2, [X|Xs], A) when X < N2 ->
    filter(N, N2, Xs, [X|A]);
filter(N, _N2, L, A) ->
    filter(N, L, A).
filter(N, [X|Xs], A) when X rem N /= 0 ->
    filter(N, Xs, [X|A]);
filter(N, [_X|Xs], A) ->
    filter(N, Xs, A);
filter(_N, [], A) ->
    lists:reverse(A).

lazy:lazy / 1 and lazy:next / 1引用伪惰性无限列表的简单实现:

lazy(L) ->
    repeat(L).

repeat(L) -> L++[fun() -> L end].

next([F]) -> F()++[F];
next(L) -> L.

由sieves生成的Prime不是一个很好的并发的地方(但它可以使用并行性检查可分性,虽然操作不够复杂,无法证明我到目前为止所写的所有并行滤波器的额外开销)。 p>

`

答案 7 :(得分:-1)

我喜欢Project Euler。

关于主要发电机的问题,我是Eratosthenes筛子的忠实粉丝。

对于2,000,000以下的数字,您可以尝试一个简单的isPrime检查实现。我不知道你在erlang中是怎么做的,但逻辑很简单。

For Each NUMBER in LIST_OF_PRIMES
     If TEST_VALUE % NUMBER == 0
          Then FALSE
END
TRUE

if isPrime == TRUE add TEST_VALUE to your LIST_OF_PRIMES

iterate starting at 14 or so with a preset list of your beginning primes. 

c#在1分钟标记

下运行了这样的列表2,000,000

编辑: 在旁注中,Eratosthenes的筛子可以轻松实现并快速运行,但是当您开始进入大型列表时会变得笨拙。最简单的实现,使用布尔数组和int值运行得非常快。问题是您开始遇到值的大小限制以及数组的长度。 - 切换到字符串或位阵实现会有所帮助,但您仍然面临着以较大值迭代列表的挑战。

答案 8 :(得分:-1)

项目欧拉问题(我会说前50个中的大多数(如果不是更多的话)主要是关于蛮力,在选择你的界限方面有着独创性。

记得测试N是否为素数(通过蛮力),你只需要看看它是否可以被任何素数(可用于平均值(sqrt(N))+ 1而不是N / 2整除。

祝你好运

答案 9 :(得分:-1)

这是一个vb版本

    'Sieve of Eratosthenes 
'http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 
'1. Create a contiguous list of numbers from two to some highest number n. 
'2. Strike out from the list all multiples of two (4, 6, 8 etc.). 
'3. The list's next number that has not been struck out is a prime number. 
'4. Strike out from the list all multiples of the number you identified in the previous step. 
'5. Repeat steps 3 and 4 until you reach a number that is greater than the square root of n (the highest number in the list). 
'6. All the remaining numbers in the list are prime. 
Private Function Sieve_of_Eratosthenes(ByVal MaxNum As Integer) As List(Of Integer)
    'tested to MaxNum = 10,000,000 - on 1.8Ghz Laptop it took 1.4 seconds
    Dim thePrimes As New List(Of Integer)
    Dim toNum As Integer = MaxNum, stpw As New Stopwatch
    If toNum > 1 Then 'the first prime is 2
        stpw.Start()
        thePrimes.Capacity = toNum 'size the list
        Dim idx As Integer
        Dim stopAT As Integer = CInt(Math.Sqrt(toNum) + 1)
        '1. Create a contiguous list of numbers from two to some highest number n.
        '2. Strike out from the list all multiples of 2, 3, 5. 
        For idx = 0 To toNum
            If idx > 5 Then
                If idx Mod 2 <> 0 _
                AndAlso idx Mod 3 <> 0 _
                AndAlso idx Mod 5 <> 0 Then thePrimes.Add(idx) Else thePrimes.Add(-1)
            Else
                thePrimes.Add(idx)
            End If
        Next
        'mark 0,1 and 4 as non-prime
        thePrimes(0) = -1
        thePrimes(1) = -1
        thePrimes(4) = -1
        Dim aPrime, startAT As Integer
        idx = 7 'starting at 7 check for primes and multiples 
        Do
            '3. The list's next number that has not been struck out is a prime number. 
            '4. Strike out from the list all multiples of the number you identified in the previous step. 
            '5. Repeat steps 3 and 4 until you reach a number that is greater than the square root of n (the highest number in the list). 
            If thePrimes(idx) <> -1 Then ' if equal to -1 the number is not a prime
                'not equal to -1 the number is a prime
                aPrime = thePrimes(idx)
                'get rid of multiples 
                startAT = aPrime * aPrime
                For mltpl As Integer = startAT To thePrimes.Count - 1 Step aPrime
                    If thePrimes(mltpl) <> -1 Then thePrimes(mltpl) = -1
                Next
            End If
            idx += 2 'increment index 
        Loop While idx < stopAT
        '6. All the remaining numbers in the list are prime. 
        thePrimes = thePrimes.FindAll(Function(i As Integer) i <> -1)
        stpw.Stop()
        Debug.WriteLine(stpw.ElapsedMilliseconds)
    End If
    Return thePrimes
End Function