Factors of an integer: Difference between revisions

→‎fac.m: Improved argument processing to minimize the non-relevant code and to tie the predicate/function declarations closer to the point of definition.
(→‎fac.m: Corrected a problem where the code would duplicate factors if they're perfect square roots.)
(→‎fac.m: Improved argument processing to minimize the non-relevant code and to tie the predicate/function declarations closer to the point of definition.)
Line 1,339:
:- implementation.
:- import_module float, getopt, int, list, math, string.
 
main(!IO) :-
io.command_line_arguments(Args, !IO),
main2list.foldl(print_arg, Args, !IO).
 
:- pred factor(int::in, list(int)::out) is det.
:- pred factor(int::in, int::in, int::in, list(int)::in, list(int)::out) is det.
:- func factor(int::in) = (list(int)::out) is det.
 
:- pred main2(list(string)::in, io::di, io::uo) is det.
 
factor(N, L) :-
Limit = float.truncate_to_int(math.sqrt(float(N))),
factor(N, 2, Limit, [1,N], L).
:- pred factor(int::in, int::in, int::in, list(int)::in, list(int)::out) is det.
factor(N, X, Z, LC, L) :-
(X > Z ->
Line 1,361:
).
 
:- func factor(int::in) = (list(int)::out) is det.
factor(N) = L :- factor(N, L).
 
:- pred main2(listprint_arg(string)::in, io::di, io::uo) is det.
main(!IO) :-
main2print_arg([]Arg, !IO) :-
io.command_line_arguments(Args, !IO),
main2(Args, !IO).
 
main2([], !IO) :-
io.write_string("Finished.\n", !IO).
 
main2([Arg|Args], !IO) :-
(string.to_int(Arg, N) ->
factor(N, X),
Line 1,383 ⟶ 1,378:
;
io.format("Bad argument: %s\n", [s(Arg)], !IO)
),.</lang>
main2(Args, !IO).</lang>
 
Use of the code looks like this:
Line 1,395 ⟶ 1,389:
factor(12345678, [1,2,3,6,9,18,47,94,141,282,423,846,14593,29186,43779,87558,131337,262674,685871,1371742,2057613,4115226,6172839,12345678])
factor(12345678) = [1,2,3,6,9,18,47,94,141,282,423,846,14593,29186,43779,87558,131337,262674,685871,1371742,2057613,4115226,6172839,12345678]
Bad argument: booger</nowiki></pre>
Finished.</nowiki></pre>
 
=={{header|MUMPS}}==