Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Moved lcm and gcd functions to mymath module

  • Loading branch information...
commit 219e092038dc24c517c9c328a7fe7b2b65f431cd 1 parent 6241c3e
authored February 27, 2010

Showing 2 changed files with 26 additions and 13 deletions. Show diff stats Hide diff stats

  1. 24  mymath.erl
  2. 15  p005.erl
24  mymath.erl
... ...
@@ -1,5 +1,5 @@
1 1
 -module(mymath).
2  
--export([primes_upto/1]).
  2
+-export([lcm/2, primes_upto/1]).
3 3
 -include_lib("eunit/include/eunit.hrl").
4 4
 
5 5
 %% Find all prime numbers upto specified value.
@@ -36,6 +36,21 @@ sieve([H|T], N) when H rem N =/= 0 -> [H | sieve(T, N)];
36 36
 sieve([_H|T], N) -> sieve(T, N); 
37 37
 sieve([], _N) -> [].
38 38
 
  39
+
  40
+%% Least common multiple of two integers
  41
+%% http://en.wikipedia.org/wiki/Least_common_multiple
  42
+%%
  43
+lcm(A, B) -> (A * B) div gcd(A, B).
  44
+
  45
+
  46
+%% Greatest common divisor of two integers
  47
+%% http://en.wikipedia.org/wiki/Greatest_common_divisor
  48
+%%
  49
+gcd(A, B) when A < B -> gcd(B, A);
  50
+gcd(A, 0) -> A;
  51
+gcd(A, B) -> gcd(B, A rem B).
  52
+
  53
+
39 54
 %% Tests
40 55
 
41 56
 primes_upto_30_test() ->
@@ -44,9 +59,14 @@ primes_upto_30_test() ->
44 59
 primes_upto_2m_test() ->
45 60
     ?assertEqual(1999993, lists:last(primes_upto(2000000))).
46 61
 
47  
-
48 62
 euler_sieve_test() ->
49 63
     ?assertEqual([2, 3, 5, 7, 11, 13, 17, 19, 23, 29], euler_sieve(lists:seq(2, 30))).
50 64
 
51 65
 eratosthenes_sieve_test() ->
52 66
     ?assertEqual([2, 3, 5, 7, 11, 13, 17, 19, 23, 29], eratosthenes_sieve(lists:seq(2, 30))).
  67
+
  68
+lcm_test() ->
  69
+    ?assertEqual(12, lcm(4, 6)).
  70
+
  71
+gcd_test() ->
  72
+    ?assertEqual(6, gcd(84, 18)).
15  p005.erl
@@ -15,23 +15,16 @@
15 15
 %% http://basildoncoder.com/blog/2008/06/10/project-euler-problem-5/
16 16
 %% ---------------------
17 17
 
18  
-find(Max) -> lists:foldl(fun lcm/2, 1, lists:seq(1, Max)).
  18
+find(Max) -> lcm(lists:seq(1, Max)).
19 19
 
20  
-lcm(A, B) -> (A * B) div gcd(A, B).
21 20
 
22  
-gcd(A, B) when A < B -> gcd(B, A);
23  
-gcd(A, 0) -> A;
24  
-gcd(A, B) -> gcd(B, A rem B).
  21
+%% Least common multiple of list of integers
  22
+%%
  23
+lcm(List) -> lists:foldl(fun mymath:lcm/2, 1, List).
25 24
 
26 25
 
27 26
 %% Tests
28 27
 
29  
-gcd_test() ->
30  
-    ?assertEqual(6, gcd(84, 18)).
31  
-
32  
-lcm_test() ->
33  
-    ?assertEqual(12, lcm(4, 6)).
34  
-
35 28
 find_10_test() ->
36 29
     ?assertEqual(2520, find(10)).
37 30
 

0 notes on commit 219e092

Please sign in to comment.
Something went wrong with that request. Please try again.