How to resolve the algorithm Gapful numbers step by step in the Erlang programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Gapful numbers step by step in the Erlang programming language
Table of Contents
Problem Statement
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only numbers ≥ 100 will be considered for this Rosetta Code task.
187 is a gapful number because it is evenly divisible by the number 17 which is formed by the first and last decimal digits of 187.
About 7.46% of positive integers are gapful.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Gapful numbers step by step in the Erlang programming language
Source code in the erlang programming language
-module(gapful).
-export([first_digit/1, last_digit/1, bookend_number/1, is_gapful/1]).
first_digit(N) ->
list_to_integer(string:slice(integer_to_list(N),0,1)).
last_digit(N) -> N rem 10.
bookend_number(N) -> 10 * first_digit(N) + last_digit(N).
is_gapful(N) -> (N >= 100) and (0 == N rem bookend_number(N)).
-module(stream).
-export([yield/1, naturals/0, naturals/1, filter/2, take/2, to_list/1]).
yield(F) when is_function(F) -> F().
naturals() -> naturals(1).
naturals(N) -> fun() -> {N, naturals(N+1)} end.
filter(Pred, Stream) ->
fun() -> do_filter(Pred, Stream) end.
do_filter(Pred, Stream) ->
case yield(Stream) of
{X, Xs} ->
case Pred(X) of
true -> {X, filter(Pred, Xs)};
false -> do_filter(Pred, Xs)
end;
halt -> halt
end.
take(N, Stream) when N >= 0 ->
fun() ->
case yield(Stream) of
{X, Xs} ->
case N of
0 -> halt;
_ -> {X, take(N - 1, Xs)}
end;
halt -> halt
end
end.
to_list(Stream) -> to_list(Stream, []).
to_list(Stream, Acc) ->
case yield(Stream) of
{X, Xs} -> to_list(Xs, [X|Acc]);
halt -> lists:reverse(Acc)
end.
-module(gapful_demo).
-mode(compile).
report_range([Start, Size]) ->
io:fwrite("The first ~w gapful numbers >= ~w:~n~w~n~n", [Size, Start,
stream:to_list(stream:take(Size, stream:filter(fun gapful:is_gapful/1,
stream:naturals(Start))))]).
main(_) -> lists:map(fun report_range/1, [[1,30],[1000000,15],[1000000000,10]]).
You may also check:How to resolve the algorithm UTF-8 encode and decode step by step in the Perl programming language
You may also check:How to resolve the algorithm Color wheel step by step in the Run BASIC programming language
You may also check:How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the PowerShell programming language
You may also check:How to resolve the algorithm O'Halloran numbers step by step in the Raku programming language
You may also check:How to resolve the algorithm Boustrophedon transform step by step in the Maxima programming language