-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha4.erl
More file actions
38 lines (30 loc) · 765 Bytes
/
a4.erl
File metadata and controls
38 lines (30 loc) · 765 Bytes
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
-module(a4).
-connect_all false.
-export([a3/2]).
a3(N,T) ->
Split = N div T,
Remainder = N rem T,
math:sqrt(makeThreads(Split,Remainder,T,1)).
makeThreads(Split,Remainder,T,I) when I < T ->
Parent = self(),
Min = Split*(I-1) + 1,
Max = Split*I,
spawn(fun() -> count(Parent,Min,Max,0) end),
SubTotal = makeThreads(Split,Remainder,T,I+1),
receive
Total -> Total
end,
SubTotal + Total;
makeThreads(Split,Remainder,T,I) when I == T ->
Parent = self(),
Min = Split*I - Split + 1,
Max = Split*I + Remainder,
spawn(fun() -> count(Parent,Min,Max,0) end),
receive
Total -> Total
end,
Total.
count(Parent,Min, Max, Total) when Min =< Max ->
count(Parent,Min+1,Max,Total+Min);
count(Parent,Min,Max, Total) when Min > Max ->
Parent ! Total.