Factors of an integer: Difference between revisions

Content added Content deleted
m (→‎using Prime decomposition: using TIO.RUN .delete text accidently inserted by middle mouse click)
(→‎optimized version: further optimized the code using memoization.)
Line 5,261:
 
It also displays a final count of the number of primes found.
 
This REXX version is about &nbsp; '''22%''' &nbsp; faster than the alternate REXX version &nbsp; (2<sup>nd</sup> version).
<lang rexx>/*REXX program displays divisors of any [negative/zero/positive] integer or a range.*/
parse arg LO HI inc . /*obtain the optional args*/
Line 5,268 ⟶ 5,270:
say center('n', w) "#divisors" center('divisors', 60) /*display the header. */
say copies('═', w) "═════════" copies('═' , 60) /* " " separator. */
pn=0 0 /*count of prime numbers. */
do k=2 until sq.k>=HI; sq.k= k*k /*memoization for squares.*/
end /*k*/
 
do n=LO to HI by inc; $= divs(n); #= words($) /*get list of divs; # divs*/
if $==! then do; #= !; $= ' (infinite)'; end /*handle case for infinity*/
Line 5,279 ⟶ 5,284:
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
divs: procedure expose sq.; parse arg x 1 b; a= 1 /*set X and B to the 1st argument. */
if x<2 then do; x= abs(x); if x==1 then return 1; if x==0 then return '∞'; b=x
end
odd= x // 2 /* [↓] process EVEN or ODD ints. ___*/
do j=2+odd by 1+odd while j*sq.j<x /*divide by all the integers up to √ x */
if x//j==0 then do; a=a j; b=x%j b; end /*÷? Add divisors to α and ß lists*/
end /*j*/ /* [↑] % ≡ integer division. ___*/
if j*sq.j==x then return a j b /*Was X a square? Then insert √ x */
return a b /*return the divisors of both lists. */</lang>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> -6 &nbsp; 200 </tt>}}