Lucas-Lehmer test for Mersenne numbers (Erlang)
From LiteratePrograms
This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.
-module(lucas_lehmer).
-export([lucas_lehmer/1]).
lucas_lehmer(P) ->
M = pow(2, P) - 1,
lucas_lehmer(P, M, 4, P - 2).
lucas_lehmer(_, _, S, I) when I == 0 ->
if
S == 0 ->
prime;
true ->
composite
end;
lucas_lehmer(P, M, S0, I) ->
S = ((S0 * S0) - 2) rem M,
lucas_lehmer(P, M, S, I - 1).
%% Replace math:pow/2 which return a float
pow(_Base, 0) ->
1;
pow(Base, Exponent) when Exponent rem 2 =:= 1 ->
Base * pow(Base, Exponent-1);
pow(Base, Exponent) when Exponent rem 2 =:= 0 ->
pow(Base*Base, Exponent div 2).
| Download code |