Skip to content
Browse files

Moved lcm and gcd functions to mymath module

  • Loading branch information...
1 parent 6241c3e commit 219e092038dc24c517c9c328a7fe7b2b65f431cd Andrey Paramonov committed Feb 27, 2010
Showing with 26 additions and 13 deletions.
  1. +22 −2 mymath.erl
  2. +4 −11 p005.erl
View
24 mymath.erl
@@ -1,5 +1,5 @@
-module(mymath).
--export([primes_upto/1]).
+-export([lcm/2, primes_upto/1]).
-include_lib("eunit/include/eunit.hrl").
%% Find all prime numbers upto specified value.
@@ -36,6 +36,21 @@ sieve([H|T], N) when H rem N =/= 0 -> [H | sieve(T, N)];
sieve([_H|T], N) -> sieve(T, N);
sieve([], _N) -> [].
+
+%% Least common multiple of two integers
+%% http://en.wikipedia.org/wiki/Least_common_multiple
+%%
+lcm(A, B) -> (A * B) div gcd(A, B).
+
+
+%% Greatest common divisor of two integers
+%% http://en.wikipedia.org/wiki/Greatest_common_divisor
+%%
+gcd(A, B) when A < B -> gcd(B, A);
+gcd(A, 0) -> A;
+gcd(A, B) -> gcd(B, A rem B).
+
+
%% Tests
primes_upto_30_test() ->
@@ -44,9 +59,14 @@ primes_upto_30_test() ->
primes_upto_2m_test() ->
?assertEqual(1999993, lists:last(primes_upto(2000000))).
-
euler_sieve_test() ->
?assertEqual([2, 3, 5, 7, 11, 13, 17, 19, 23, 29], euler_sieve(lists:seq(2, 30))).
eratosthenes_sieve_test() ->
?assertEqual([2, 3, 5, 7, 11, 13, 17, 19, 23, 29], eratosthenes_sieve(lists:seq(2, 30))).
+
+lcm_test() ->
+ ?assertEqual(12, lcm(4, 6)).
+
+gcd_test() ->
+ ?assertEqual(6, gcd(84, 18)).
View
15 p005.erl
@@ -15,23 +15,16 @@
%% http://basildoncoder.com/blog/2008/06/10/project-euler-problem-5/
%% ---------------------
-find(Max) -> lists:foldl(fun lcm/2, 1, lists:seq(1, Max)).
+find(Max) -> lcm(lists:seq(1, Max)).
-lcm(A, B) -> (A * B) div gcd(A, B).
-gcd(A, B) when A < B -> gcd(B, A);
-gcd(A, 0) -> A;
-gcd(A, B) -> gcd(B, A rem B).
+%% Least common multiple of list of integers
+%%
+lcm(List) -> lists:foldl(fun mymath:lcm/2, 1, List).
%% Tests
-gcd_test() ->
- ?assertEqual(6, gcd(84, 18)).
-
-lcm_test() ->
- ?assertEqual(12, lcm(4, 6)).
-
find_10_test() ->
?assertEqual(2520, find(10)).

0 comments on commit 219e092

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