Factors of an integer: Difference between revisions

Content added Content deleted
(Added some LFE examples)
Line 1,251: Line 1,251:
#:'f' 3491888400+!10
#:'f' 3491888400+!10
1920 16 4 4 12 16 32 16 8 24</lang>
1920 16 4 4 12 16 32 16 8 24</lang>

=={{header|LFE}}==

===Using List Comprehensions===

This following function is elegant looking and concise. However, it will not handle large numbers well: it will consume a great deal of memory (on one large number, the function consumed 4.3GB of memory on my desktop machine):
<lang lisp>
(defun factors (n)
(list-comp
((<- i (when (== 0 (rem n i))) (lists:seq 1 (trunc (/ n 2)))))
i))
</lang>

===Non-Stack-Consuming===

This version will not consume the stack (this function only used 18MB of memory on my machine with a ridiculously large number):
<lang lisp>
(defun factors (n)
"Tail-recursive prime factors function."
(factors n 2 '()))

(defun factors
((1 _ acc) acc)
((n _ acc) (when (=< n 0))
#(error undefined))
((n k acc) (when (== 0 (rem n k)))
(factors (div n k) k (cons k acc)))
((n k acc)
(factors n (+ k 1) acc)))
</lang>

Output in the REPL:
<lang lisp>
> (factors 10677106534462215678539721403561279)
(104729 104729 104729 98731 98731 32579 29269)
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==