Factors of an integer: Difference between revisions

Content added Content deleted
(Add min)
Line 2,152: Line 2,152:
64 .factors
64 .factors
100 .factors</lang>
100 .factors</lang>
=== Alternative version with vectored execution ===
It's not really idiomatic FORTH to leave a variable number of items on the stack, so instead this version repeatedly calls an execution token for each factor, and it uses a defining word to create a fold over the factors of an integer. This version also only tests up to the square root, which means that items are generated in pairs, rather than in sorted order.
<lang FORTH>
: sq s" dup *" evaluate ; immediate

: factors ( n a xt -- )
swap 2>r 1
BEGIN 2dup sq > WHILE
2dup /mod swap 0= IF
over
r> r@ execute >r
r> r@ execute >r
ELSE
drop
THEN 1+
REPEAT
2dup sq = IF
2r> swap execute nip
ELSE
2drop r> rdrop
THEN ;

: <with-factors>
create 2, does> 2@ factors ;

0 :noname nip 1+ ; <with-factors> count-factors
0 ' + <with-factors> sum-factors

0 :noname swap . ; <with-factors> (.factors)
: .factors (.factors) drop ;
</lang>
{{Out}}
<pre>
100 .factors 1 100 2 50 4 25 5 20 10 ok
100 count-factors . 9 ok
100 sum-factors . 217 ok
1 100 + 2 + 50 + 4 + 25 + 5 + 20 + 10 + . 217 ok \ test sum-factors result
77 .factors 1 77 7 11 ok
108 .factors 1 108 2 54 3 36 4 27 6 18 9 12 ok
</pre>


=={{header|Fortran}}==
=={{header|Fortran}}==