Factors of an integer: Difference between revisions
Content added Content deleted
(→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: | Line 1,339: | ||
:- implementation. |
:- implementation. |
||
:- import_module float, getopt, int, list, math, string. |
:- import_module float, getopt, int, list, math, string. |
||
⚫ | |||
⚫ | |||
⚫ | |||
:- pred factor(int::in, list(int)::out) is det. |
:- pred factor(int::in, list(int)::out) is det. |
||
⚫ | |||
⚫ | |||
⚫ | |||
factor(N, L) :- |
factor(N, L) :- |
||
Limit = float.truncate_to_int(math.sqrt(float(N))), |
Limit = float.truncate_to_int(math.sqrt(float(N))), |
||
factor(N, 2, Limit, [1,N], L). |
factor(N, 2, Limit, [1,N], L). |
||
⚫ | |||
factor(N, X, Z, LC, L) :- |
factor(N, X, Z, LC, L) :- |
||
(X > Z -> |
(X > Z -> |
||
Line 1,361: | Line 1,361: | ||
). |
). |
||
⚫ | |||
factor(N) = L :- factor(N, L). |
factor(N) = L :- factor(N, L). |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
io.write_string("Finished.\n", !IO). |
|||
main2([Arg|Args], !IO) :- |
|||
(string.to_int(Arg, N) -> |
(string.to_int(Arg, N) -> |
||
factor(N, X), |
factor(N, X), |
||
Line 1,383: | Line 1,378: | ||
; |
; |
||
io.format("Bad argument: %s\n", [s(Arg)], !IO) |
io.format("Bad argument: %s\n", [s(Arg)], !IO) |
||
) |
).</lang> |
||
main2(Args, !IO).</lang> |
|||
Use of the code looks like this: |
Use of the code looks like this: |
||
Line 1,395: | Line 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]) |
||
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 |
Bad argument: booger</nowiki></pre> |
||
Finished.</nowiki></pre> |
|||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |