Factors of an integer: Difference between revisions

→‎fac.m: Replaced implementation with a tail-recursive implementation that does magic.
(→‎fac.m: Replaced implementation with a tail-recursive implementation that does magic.)
Line 1,287:
 
:- implementation.
:- import_module float, getopt, int, list, math, string.
 
main(!IO) :-
Line 1,302:
factor(N, L) :-
Limit = float.truncate_to_int(math.sqrt(float(N))),
factor(N, 2, Limit, [1L0),N], L).
list.sort_and_remove_dups([1, N | L0], L).
:- pred factor(int::in, int::in, int::in, list(int)::in, list(int)::out) is det.
factor(N, X, Z, LC, LL0) :-
(X > Z ->
list.sort_and_remove_dups(LC,L0 L)= []
;
(0 = N mod X ->
factor(N,L0 X + 1, Z,= [X, N / X | LCL], L)
;
factor(N,L0 X + 1, Z, LC,= L)
),
factor(N, X + 1, Z, L)
).