edbond (owner)

Revisions

  • bbe25b edbond Wed Jul 08 05:12:54 -0700 2009
gist: 142769 Download_button fork
public
Description:
erlang solution to project euler 224
Public Clone URL: git://gist.github.com/142769.git
Embed All Files: show embed
Erlang #
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
-module(e224).
-compile(export_all).
%-export([start/0]).
 
%-define(LIM, 75000000).
-define(LIM, 75000000).
 
%% 7500 -> 311 ? 419 ?
 
%-- http://projecteuler.net/index.php?section=problems&id=224
%--
%-- Let us call an integer sided triangle with sides a ≤ b ≤ c barely obtuse if the sides satisfy
%-- a^(2) + b^(2) = c^(2) - 1.
%-- How many barely obtuse triangles are there with perimeter ≤ 75,000,000?
 
solution(A,_B,S,_Step) when A > ?LIM/3 -> leader ! {result, S};
 
solution(A,B,S, Step) when B > ?LIM ->
  solution(A+Step, A+Step, S, Step);
 
solution(A,B,S, Step) ->
  C = math:sqrt(1+A*A+B*B),
  TC = trunc(C),
  P = A+B+TC,
  case (P =< ?LIM) and (C >= A) and (C >= B) and (B >= A) and (C == TC) of
    true ->
      %io:format("solution: ~p~n", [{A,B,C, A*A+B*B, (C*C)-1, P}]),
      S1 = S+1;
    false -> S1 = S
  end,
  solution(A,B+2,S1, Step).
 
collect(0, S) -> S;
collect(N, S) ->
  receive
    {result, R} ->
      S1 = S+R,
      collect(N-1, S1)
  end.
 
start() ->
  register(leader, self()),
 
  T1 = now(),
 
  Procs = 2,
  Step = Procs*2, % number of processes * 2
 
  spawn(?MODULE, solution, [2,2,0, Step]),
  spawn(?MODULE, solution, [4,4,0, Step]),
 
  S = collect(Procs, 0),
  T2 = now(),
 
  io:format("Result: ~w (~w ms)~n", [S, timer:now_diff(T2,T1)/1000 ]),
  unregister(leader),
  ok.