Factors of an integer: Difference between revisions

add Refal
(add Refal)
 
(42 intermediate revisions by 21 users not shown)
Line 29:
 
=={{header|0815}}==
<langsyntaxhighlight lang="0815">
<:1:~>|~#:end:>~x}:str:/={^:wei:~%x<:a:x=$~
=}:wei:x<:1:+{>~>x=-#:fin:^:str:}:fin:{{~%
</syntaxhighlight>
</lang>
 
=={{header|11l}}==
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F factor(n)
V factors = Set[Int]()
L(x) 1..Int(sqrt(n))
Line 46:
 
L(i) (45, 53, 64)
print(i‘: factors: ’String(factor(i)))</langsyntaxhighlight>
 
{{out}}
Line 57:
=={{header|360 Assembly}}==
Very compact version.
<langsyntaxhighlight lang="360asm">* Factors of an integer - 07/10/2015
FACTOR CSECT
USING FACTOR,R15 set base register
Line 79:
PG DC CL132' ' buffer
YREGS
END FACTOR</langsyntaxhighlight>
{{out}}
<pre>
Line 86:
 
=={{header|68000 Assembly}}==
<langsyntaxhighlight lang="68000devpac">;max input range equals 0 to 0xFFFFFFFF.
 
 
Line 113:
 
 
;end of program</langsyntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program factorst64.s */
Line 291:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun factors-r (n i)
(declare (xargs :measure (nfix (- n i))))
(cond ((zp (- n i))
Line 303:
 
(defun factors (n)
(factors-r n 1))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintFactors(CARD a)
BYTE notFirst
CARD p
Line 338:
Test(6502)
Test(12345)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Factors_of_an_integer.png Screenshot from Atari 8-bit computer]
Line 352:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function factor(n:uint):Vector.<uint>
{
var factors:Vector.<uint> = new Vector.<uint>();
Line 358:
if(n % i == 0)factors.push(i);
return factors;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Command_Line;
procedure Factors is
Line 382:
end loop;
Ada.Text_IO.Put_Line (Positive'Image (Number) & ".");
end Factors;</langsyntaxhighlight>
 
=={{header|Aikido}}==
<langsyntaxhighlight lang="aikido">import math
 
function factor (n:int) {
Line 418:
printvec (factor (45))
printvec (factor (25))
printvec (factor (100))</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 428:
 
Note: The following implements generators, eliminating the need of declaring arbitrarily long '''int''' arrays for caching.
<langsyntaxhighlight lang="algol68">MODE YIELDINT = PROC(INT)VOID;
 
PROC gen factors = (INT n, YIELDINT yield)VOID: (
Line 452:
# OD # ));
print(new line)
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 461:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% return the factors of n ( n should be >= 1 ) in the array factor %
% the bounds of factor should be 0 :: len (len must be at least 1) %
Line 512:
for i := 1 until 100 do testFactorsOf( i )
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 529:
=={{header|ALGOL-M}}==
Instead of displaying 1 and the number itself as factors, prime numbers are explicitly reported as such. To reduce the number of test divisions, only odd divisors are tested if an initial check shows the number to be factored is not even. The upper limit of divisors is set at N/2 or N/3, depending on whether N is even or odd, and is continuously reduced to N divided by the next potential divisor until the first factor is found. For a prime number the resulting limit will be the square root of N, which avoids the necessity of explicitly calculating that value. (ALGOL-M does not have a built-in square root function.)
<langsyntaxhighlight lang="algol">
BEGIN
 
Line 580:
DONE: WRITE ("GOODBYE");
 
END</langsyntaxhighlight>
{{out}}
<pre>NUMBER TO FACTOR (OR 0 TO QUIT):
Line 599:
 
=={{header|APL}}==
<langsyntaxhighlight APLlang="apl"> factors←{(0=(⍳⍵)|⍵)/⍳⍵}
factors 12345
1 3 5 15 823 2469 4115 12345
factors 720
1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 30 36 40 45 48 60 72 80 90 120 144 180 240 360 720</langsyntaxhighlight>
 
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">-- integerFactors :: Int -> [Int]
on integerFactors(n)
if n = 1 then
Line 702:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120}</langsyntaxhighlight>
----
 
===Straightforward===
 
<langsyntaxhighlight lang="applescript">on factors(n)
set output to {}
Line 728:
end factors
 
factors(123456789)</langsyntaxhighlight>
 
{{output}}
 
<langsyntaxhighlight lang="applescript">{1, 3, 9, 3607, 3803, 10821, 11409, 32463, 34227, 13717421, 41152263, 123456789}</langsyntaxhighlight>
 
=={{header|Arc}}==
<syntaxhighlight lang="arc">
<lang Arc>
(= divisor (fn (num)
(= dlist '())
Line 748:
 
(map [rev _] (map [divisor _] '(45 53 60 64)))
</syntaxhighlight>
</lang>
 
{{Out}}
<syntaxhighlight lang="arc">
<lang Arc>
'(
(1 3 5 9 15 45)
Line 758:
(1 2 4 8 16 32 64)
)
</syntaxhighlight>
</lang>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program factorst.s */
Line 949:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">factors: $[num][
select 1..num [x][
(num%x)=0
Line 958:
]
 
print factors 36</langsyntaxhighlight>
{{out}}
 
<pre>1 2 3 4 6 9 12 18 36</pre>
 
=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">int[] n = {11, 21, 32, 45, 67, 519};
 
for(var j : n) {
write(j, suffix=none);
write(" =>", suffix=none);
for(int i = 1; i < (j/2); ++i) {
if(j % i == 0) {
write(" ", i, suffix=none);
}
}
write(" ", j);
}</syntaxhighlight>
{{out}}
<pre>11 => 1 11
21 => 1 3 7 21
32 => 1 2 4 8 32
45 => 1 3 5 9 15 45
67 => 1 67
519 => 1 3 173 519</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">msgbox, % factors(45) "`n" factors(53) "`n" factors(64)
 
Factors(n)
Line 973 ⟶ 994:
Sort, v, N U D,
Return, v
}</langsyntaxhighlight>
 
{{out}}
Line 982 ⟶ 1,003:
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">;AutoIt Version: 3.2.10.0
$num = 45
MsgBox (0,"Factors", "Factors of " & $num & " are: " & factors($num))
Line 994 ⟶ 1,015:
Next
Return $ls_factors&$intg
EndFunc</langsyntaxhighlight>
 
{{out}}
Line 1,002 ⟶ 1,023:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f FACTORS_OF_AN_INTEGER.AWK
BEGIN {
Line 1,021 ⟶ 1,042:
printf("\n")
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,038 ⟶ 1,059:
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{works with|QBasic}}
The [[Factors_of_an_integer#Sinclair ZX81 BASIC]] code works the same in Applesoft BASIC.
This example stores the factors in a shared array (with the original number as the last element) for later retrieval.
 
Note that this will error out if you pass 32767 (or higher).
<lang qbasic>DECLARE SUB factor (what AS INTEGER)
 
REDIM SHARED factors(0) AS INTEGER
 
DIM i AS INTEGER, L AS INTEGER
 
INPUT "Gimme a number"; i
 
factor i
 
PRINT factors(0);
FOR L = 1 TO UBOUND(factors)
PRINT ","; factors(L);
NEXT
PRINT
 
SUB factor (what AS INTEGER)
DIM tmpint1 AS INTEGER
DIM L0 AS INTEGER, L1 AS INTEGER
 
REDIM tmp(0) AS INTEGER
REDIM factors(0) AS INTEGER
factors(0) = 1
 
FOR L0 = 2 TO what
IF (0 = (what MOD L0)) THEN
'all this REDIMing and copying can be replaced with:
'REDIM PRESERVE factors(UBOUND(factors)+1)
'in languages that support the PRESERVE keyword
REDIM tmp(UBOUND(factors)) AS INTEGER
FOR L1 = 0 TO UBOUND(factors)
tmp(L1) = factors(L1)
NEXT
REDIM factors(UBOUND(factors) + 1)
FOR L1 = 0 TO UBOUND(factors) - 1
factors(L1) = tmp(L1)
NEXT
factors(UBOUND(factors)) = L0
END IF
NEXT
END SUB</lang>
 
{{out}}
<pre>
Gimme a number? 17
1 , 17
Gimme a number? 12345
1 , 3 , 5 , 15 , 823 , 2469 , 4115 , 12345
Gimme a number? 32765
1 , 5 , 6553 , 32765
Gimme a number? 32766
1 , 2 , 3 , 6 , 43 , 86 , 127 , 129 , 254 , 258 , 381 , 762 , 5461 , 10922 ,
16383 , 32766
</pre>
 
==={{header|ASIC}}===
{{trans|GW-BASIC}}
<syntaxhighlight lang="basic">REM Factors of an integer
<lang basic>
REM Factors of an integer
PRINT "Enter an integer";
LOOP:
Line 1,114 ⟶ 1,078:
NEXT I
PRINT NA
END</langsyntaxhighlight>
{{out}}
<pre>Enter an integer?60
1 2 3 4 5 6 10 12 15 20 30 60</pre>
Enter an integer?60
1 2 3 4 5 6 10 12 15 20 30 60
 
</pre>
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
subroutine printFactors(n)
print n; " => ";
Line 1,139 ⟶ 1,100:
call printFactors(67)
call printFactors(96)
end</syntaxhighlight>
end
 
</lang>
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
sort% = FN_sortinit(0, 0)
PRINT "The factors of 45 are " FNfactorlist(45)
PRINT "The factors of 12345 are " FNfactorlist(12345)
END
DEF FNfactorlist(N%)
LOCAL C%, I%, L%(), L$
DIM L%(32)
FOR I% = 1 TO SQR(N%)
IF (N% MOD I% = 0) THEN
L%(C%) = I%
C% += 1
IF (N% <> I%^2) THEN
L%(C%) = (N% DIV I%)
C% += 1
ENDIF
ENDIF
NEXT I%
CALL sort%, L%(0)
FOR I% = 0 TO C%-1
L$ += STR$(L%(I%)) + ", "
NEXT
= LEFT$(LEFT$(L$))</syntaxhighlight>
{{out}}
<pre>The factors of 45 are 1, 3, 5, 9, 15, 45
The factors of 12345 are 1, 3, 5, 15, 823, 2469, 4115, 12345</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">10 cls
20 printfactors(11)
30 printfactors(21)
40 printfactors(32)
50 printfactors(45)
60 printfactors(67)
70 printfactors(96)
80 end
100 sub printfactors(n)
110 if n < 1 then printfactors = 0
120 print n "=> ";
130 for i = 1 to n/2
140 if n mod i = 0 then print i " ";
150 next i
160 print n
170 end sub</syntaxhighlight>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">do
 
input "enter an integer", n
 
loop n = 0
 
let a = abs(n)
 
for i = 1 to int(a / 2)
 
if a = int(a / i) * i then
 
print i
 
endif
 
next i
 
print a</syntaxhighlight>
{{out| Output}}<pre>?60
1 2 3 4 5 6 10 12 15 20 30 60</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub printFactors(n As Integer)
If n < 1 Then Return
Print n; " =>";
For i As Integer = 1 To n / 2
If n Mod i = 0 Then Print i; " ";
Next i
Print n
End Sub
 
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
{{out}}
<pre>
11 => 1 11
Igual que la entrada de FreeBASIC.
21 => 1 3 7 21
32 => 1 2 4 8 16 32
45 => 1 3 5 9 15 45
67 => 1 67
96 => 1 2 3 4 6 8 12 16 24 32 48 96
</pre>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">window 1, @"Factors of an Integer", (0,0,1000,270)
 
clear local mode
local fn IntegerFactors( f as long ) as CFStringRef
long i, s, l(100), c = 0
CFStringRef factorStr = @""
for i = 1 to sqr(f)
if ( f mod i == 0 )
l(c) = i
c++
if ( f != i ^ 2 )
l(c) = ( f / i )
c++
end if
end if
next i
s = 1
while ( s = 1 )
s = 0
for i = 0 to c-1
if l(i) > l(i+1) and l(i+1) != 0
swap l(i), l(i+1)
s = 1
end if
next i
wend
for i = 0 to c - 1
if ( i < c - 1 )
factorStr = fn StringWithFormat( @"%@ %ld, ", factorStr, l(i) )
else
factorStr = fn StringWithFormat( @"%@ %ld", factorStr, l(i) )
end if
next
end fn = factorStr
 
print @"Factors of 25 are:"; fn IntegerFactors( 25 )
print @"Factors of 45 are:"; fn IntegerFactors( 45 )
print @"Factors of 103 are:"; fn IntegerFactors( 103 )
print @"Factors of 760 are:"; fn IntegerFactors( 760 )
print @"Factors of 12345 are:"; fn IntegerFactors( 12345 )
print @"Factors of 32766 are:"; fn IntegerFactors( 32766 )
print @"Factors of 32767 are:"; fn IntegerFactors( 32767 )
print @"Factors of 57097 are:"; fn IntegerFactors( 57097 )
print @"Factors of 12345678 are:"; fn IntegerFactors( 12345678 )
print @"Factors of 32434243 are:"; fn IntegerFactors( 32434243 )
 
HandleEvents</syntaxhighlight>
{{out}}
<pre>Factors of 25 are: 1, 5, 25
Factors of 45 are: 1, 3, 5, 9, 15, 45
Factors of 103 are: 1, 103
Factors of 760 are: 1, 2, 4, 5, 8, 10, 19, 20, 38, 40, 76, 95, 152, 190, 380, 760
Factors of 12345 are: 1, 3, 5, 15, 823, 2469, 4115, 12345
Factors of 32766 are: 1, 2, 3, 6, 43, 86, 127, 129, 254, 258, 381, 762, 5461, 10922, 16383, 32766
Factors of 32767 are: 1, 7, 31, 151, 217, 1057, 4681, 32767
Factors of 57097 are: 1, 57097
Factors of 12345678 are: 1, 2, 3, 6, 9, 18, 47, 94, 141, 282, 423, 846, 14593, 29186, 43779, 87558, 131337, 262674, 685871, 1371742, 2057613, 4115226, 6172839, 12345678
Factors of 32434243 are: 1, 307, 105649, 32434243</pre>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
 
End
 
Sub printFactors(n As Integer)
 
If n < 1 Then Return
Print n; " =>";
For i As Integer = 1 To n / 2
If n Mod i = 0 Then Print i; " ";
Next
Print n
 
End Sub</syntaxhighlight>
 
==={{header|GW-BASIC}}===
<syntaxhighlight lang="qbasic">
<lang gwbasic>
10 INPUT "Enter an integer: ", N
20 IF N = 0 THEN GOTO 10
Line 1,155 ⟶ 1,302:
50 IF NA MOD I = 0 THEN PRINT I;
60 NEXT I
70 PRINT NA</langsyntaxhighlight>
{{out}}
<pre>
Line 1,169 ⟶ 1,316:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight IS-BASIClang="qbasic">100 PROGRAM "Factors.bas"
110 INPUT PROMPT "Number: ":N
120 FOR I=1 TO INT(N/2)
130 IF MOD(N,I)=0 THEN PRINT I;
140 NEXT
150 PRINT N</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">num = 10677106534462215678539721403561279
maxnFactors = 1000
dim primeFactors(maxnFactors), nPrimeFactors(maxnFactors)
global nDifferentPrimeNumbersFound, nFactors, iFactor
 
print "Start finding all factors of ";num; ":"
 
nDifferentPrimeNumbersFound=0
dummy = factorize(num,2)
nFactors = showPrimeFactors(num)
dim factors(nFactors)
dummy = generateFactors(1,1)
sort factors(), 0, nFactors-1
for i=1 to nFactors
print i;" ";factors(i-1)
next i
 
print "done"
 
wait
 
function factorize(iNum,offset)
factorFound=0
i = offset
do
if (iNum MOD i)=0 _
then
if primeFactors(nDifferentPrimeNumbersFound) = i _
then
nPrimeFactors(nDifferentPrimeNumbersFound) = nPrimeFactors(nDifferentPrimeNumbersFound) + 1
else
nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1
primeFactors(nDifferentPrimeNumbersFound) = i
nPrimeFactors(nDifferentPrimeNumbersFound) = 1
end if
if iNum/i<>1 then dummy = factorize(iNum/i,i)
factorFound=1
end if
i=i+1
loop while factorFound=0 and i<=sqr(iNum)
if factorFound=0 _
then
nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1
primeFactors(nDifferentPrimeNumbersFound) = iNum
nPrimeFactors(nDifferentPrimeNumbersFound) = 1
end if
end function
 
function showPrimeFactors(iNum)
showPrimeFactors=1
print iNum;" = ";
for i=1 to nDifferentPrimeNumbersFound
print primeFactors(i);"^";nPrimeFactors(i);
if i<nDifferentPrimeNumbersFound then print " * "; else print ""
showPrimeFactors = showPrimeFactors*(nPrimeFactors(i)+1)
next i
end function
 
function generateFactors(product,pIndex)
if pIndex>nDifferentPrimeNumbersFound _
then
factors(iFactor) = product
iFactor=iFactor+1
else
for i=0 to nPrimeFactors(pIndex)
dummy = generateFactors(product*primeFactors(pIndex)^i,pIndex+1)
next i
end if
end function</syntaxhighlight>
{{out}}
 
<syntaxhighlight lang="lb">Start finding all factors of 10677106534462215678539721403561279:
10677106534462215678539721403561279 = 29269^1 * 32579^1 * 98731^2 * 104729^3
1 1
2 29269
3 32579
4 98731
5 104729
6 953554751
7 2889757639
8 3065313101
9 3216557249
10 3411966091
11 9747810361
12 10339998899
13 10968163441
14 94145414120981
15 99864835517479
16 285308661456109
17 302641427774831
18 317573913751019
19 321027175754629
20 336866824130521
21 357331796744339
22 1020878431297169
23 1082897744693371
24 1148684789012489
25 9295070881578575111
26 9859755075476219149
27 10458744358910058191
28 29880090805636839461
29 31695334089430275799
30 33259198413230468851
31 33620855089606540541
32 35279725624365333809
33 37423001741237879131
34 106915577231321212201
35 113410797903992051459
36 973463478356842592799919
37 1032602289299548955255621
38 1095333837964291484285239
39 3129312029983540559911069
40 3319420643851943354153471
41 3483202590619213772296379
42 3694810384914157044482761
43 11197161487859039232598529
44 101949856624833767901342716951
45 108143405156052462534965931709
46 327729719588146219298926345301
47 364792324112959639158827476291
48 10677106534462215678539721403561279
done</syntaxhighlight>
 
====A Simpler Approach====
This is a somewhat simpler approach for finding the factors of smaller numbers (less than one million).
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
print "ROSETTA CODE - Factors of an integer"
'A simpler approach for smaller numbers
[Start]
print
input "Enter an integer (< 1,000,000): "; n
n=abs(int(n)): if n=0 then goto [Quit]
if n>999999 then goto [Start]
FactorCount=FactorCount(n)
select case FactorCount
case 1: print "The factor of 1 is: 1"
case else
print "The "; FactorCount; " factors of "; n; " are: ";
for x=1 to FactorCount
print " "; Factor(x);
next x
if FactorCount=2 then print " (Prime)" else print
end select
goto [Start]
 
[Quit]
print "Program complete."
end
 
function FactorCount(n)
dim Factor(100)
for y=1 to n
if y>sqr(n) and FactorCount=1 then
'If no second factor is found by the square root of n, then n is prime.
FactorCount=2: Factor(FactorCount)=n: exit function
end if
if (n mod y)=0 then
FactorCount=FactorCount+1
Factor(FactorCount)=y
end if
next y
end function
</syntaxhighlight>
{{out}}
<pre>
ROSETTA CODE - Factors of an integer
 
Enter an integer (< 1,000,000): 1
The factor of 1 is: 1
 
Enter an integer (< 1,000,000): 2
The 2 factors of 2 are: 1 2 (Prime)
 
Enter an integer (< 1,000,000): 4
The 3 factors of 4 are: 1 2 4
 
Enter an integer (< 1,000,000): 6
The 4 factors of 6 are: 1 2 3 6
 
Enter an integer (< 1,000,000): 999999
The 64 factors of 999999 are: 1 3 7 9 11 13 21 27 33 37 39 63 77 91 99 111 117 143 189 231 259 273 297 333 351 407 429 481 693 777 819 999 1001 1221 1287 1443 2079 2331 2457 2849 3003 3367 3663 3861 4329 5291 6993 8547 9009 10101 10989 12987 15873 25641 27027 30303 37037 47619 76923 90909 111111 142857 333333 999999
 
Enter an integer (< 1,000,000):
Program complete.
</pre>
 
==={{header|Minimal BASIC}}===
{{trans|GW-BASIC}}
{{works with|Commodore BASIC}}
{{works with|IS-BASIC}}
{{works with|MSX BASIC|any}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="qbasic">10 REM Factors of an integer
<lang gwbasic>
10 REM Factors of an integer
20 PRINT "Enter an integer";
30 INPUT N
Line 1,191 ⟶ 1,527:
90 NEXT I
100 PRINT N1
110 END</syntaxhighlight>
 
</lang>
==={{header|MSX Basic}}===
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">10 INPUT "Enter an integer: "; N
20 IF N = 0 THEN GOTO 10
30 N1 = ABS(N)
40 FOR I = 1 TO N1/2
50 IF N1 MOD I = 0 THEN PRINT I;
60 NEXT I
70 PRINT N1</syntaxhighlight>
 
==={{header|Nascom BASIC}}===
{{trans|GW-BASIC}}
{{works with|Nascom ROM BASIC|4.7}}
<langsyntaxhighlight lang="basic">
10 REM Factors of an integer
20 INPUT "Enter an integer"; N
Line 1,207 ⟶ 1,552:
80 PRINT NA
90 END
</syntaxhighlight>
</lang>
{{out}}
<pre>Enter an integer? 60
<pre>
1 2 3 4 5 6 10 12 15 20 30 60</pre>
Enter an integer? 60
1 2 3 4 5 6 10 12 15 20 30 60
</pre>
See also [[#Minimal BASIC|Minimal BASIC]]
 
==={{header|Palo Alto Tiny BASIC}}===
{{trans|GW-BASIC}}
<syntaxhighlight lang="basic">
10 REM FACTORS OF AN INTEGER
20 INPUT "ENTER AN INTEGER"N
30 IF N=0 GOTO 20
40 LET A=ABS(N)
50 IF A=1 GOTO 90
60 FOR I=1 TO A/2
70 IF (A/I)*I=A PRINT I," ",
80 NEXT I
90 PRINT A
100 STOP
</syntaxhighlight>
{{out}}
3 runs.
<pre>ENTER AN INTEGER:1
1</pre>
<pre>ENTER AN INTEGER:60
1 2 3 4 5 6 10 12 15 20 30 60</pre>
<pre>ENTER AN INTEGER:-22222
1 2 41 82 271 542 11111 22222</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure PrintFactors(n)
Protected i, lim=Round(sqr(n),#PB_Round_Up)
NewList F.i()
For i=1 To lim
If n%i=0
AddElement(F()): F()=i
AddElement(F()): F()=n/i
EndIf
Next
;- Present the result
SortList(F(),#PB_Sort_Ascending)
ForEach F()
Print(str(F())+" ")
Next
EndProcedure
 
If OpenConsole()
Print("Enter integer to factorize: ")
PrintFactors(Val(Input()))
Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input()
EndIf</syntaxhighlight>
{{out}}
<pre> Enter integer to factorize: 96
1 2 3 4 6 8 12 16 24 32 48 96</pre>
 
==={{header|QB64}}===
<syntaxhighlight lang="qb64">'Task
'Compute the factors of a positive integer.
 
'These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
Dim Dividendum As Integer, Index As Integer
Randomize Timer
Dividendum = Int(Rnd * 1000) + 1
Print " Dividendum: "; Dividendum
Index = Int(Dividendum / 2)
print "Divisors: ";
While Index > 0
If Dividendum Mod Index = 0 Then Print Index; " ";
Index = Index - 1
Wend
End</syntaxhighlight>
 
==={{header|QBasic}}===
See [[#QuickBASIC|QuickBASIC]].
 
==={{header|QuickBASIC}}===
{{works with|QBasic}}
This example stores the factors in a shared array (with the original number as the last element) for later retrieval.
 
Note that this will error out if you pass 32767 (or higher).
<syntaxhighlight lang="qbasic">DECLARE SUB factor (what AS INTEGER)
 
REDIM SHARED factors(0) AS INTEGER
 
DIM i AS INTEGER, L AS INTEGER
 
INPUT "Gimme a number"; i
 
factor i
 
PRINT factors(0);
FOR L = 1 TO UBOUND(factors)
PRINT ","; factors(L);
NEXT
PRINT
 
SUB factor (what AS INTEGER)
DIM tmpint1 AS INTEGER
DIM L0 AS INTEGER, L1 AS INTEGER
 
REDIM tmp(0) AS INTEGER
REDIM factors(0) AS INTEGER
factors(0) = 1
 
FOR L0 = 2 TO what
IF (0 = (what MOD L0)) THEN
'all this REDIMing and copying can be replaced with:
'REDIM PRESERVE factors(UBOUND(factors)+1)
'in languages that support the PRESERVE keyword
REDIM tmp(UBOUND(factors)) AS INTEGER
FOR L1 = 0 TO UBOUND(factors)
tmp(L1) = factors(L1)
NEXT
REDIM factors(UBOUND(factors) + 1) AS INTEGER
FOR L1 = 0 TO UBOUND(factors) - 1
factors(L1) = tmp(L1)
NEXT
factors(UBOUND(factors)) = L0
END IF
NEXT
END SUB</syntaxhighlight>
{{out}}
<pre> Gimme a number? 17
1 , 17
Gimme a number? 12345
1 , 3 , 5 , 15 , 823 , 2469 , 4115 , 12345
Gimme a number? 32765
1 , 5 , 6553 , 32765
Gimme a number? 32766
1 , 2 , 3 , 6 , 43 , 86 , 127 , 129 , 254 , 258 , 381 , 762 , 5461 , 10922 ,
16383 , 32766</pre>
 
==={{header|Quite BASIC}}===
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">10 INPUT "Enter an integer: "; N
20 IF N = 0 THEN GOTO 15
30 N1 = ABS(N)
40 FOR I = 1 TO N1/2
50 IF N1 - INT(N1 / I) * I = 0 THEN PRINT I; " ";
60 NEXT I
70 PRINT N1</syntaxhighlight>
 
==={{header|REALbasic}}===
<syntaxhighlight lang="vb">Function factors(num As UInt64) As UInt64()
'This function accepts an unsigned 64 bit integer as input and returns an array of unsigned 64 bit integers
Dim result() As UInt64
Dim iFactor As UInt64 = 1
While iFactor <= num/2 'Since a factor will never be larger than half of the number
If num Mod iFactor = 0 Then
result.Append(iFactor)
End If
iFactor = iFactor + 1
Wend
result.Append(num) 'Since a given number is always a factor of itself
Return result
End Function</syntaxhighlight>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="basic">PRINT "Factors of 45 are ";factorlist$(45)
PRINT "Factors of 12345 are "; factorlist$(12345)
END
FUNCTION factorlist$(f)
DIM L(100)
FOR i = 1 TO SQR(f)
IF (f MOD i) = 0 THEN
L(c) = i
c = c + 1
IF (f <> i^2) THEN
L(c) = (f / i)
c = c + 1
END IF
END IF
NEXT i
s = 1
WHILE s = 1
s = 0
FOR i = 0 TO c-1
IF L(i) > L(i+1) AND L(i+1) <> 0 THEN
t = L(i)
L(i) = L(i+1)
L(i+1) = t
s = 1
END IF
NEXT i
WEND
FOR i = 0 TO c-1
factorlist$ = factorlist$ + STR$(L(i)) + ", "
NEXT
END FUNCTION</syntaxhighlight>
{{out}}
<pre>Factors of 45 are 1, 3, 5, 9, 15, 45,
Factors of 12345 are 1, 3, 5, 15, 823, 2469, 4115, 12345, </pre>
 
==={{header|Sinclair ZX81 BASIC}}===
{{works with|Applesoft BASIC}}
<lang basic>10 INPUT N
<syntaxhighlight lang="basic">10 INPUT N
20 FOR I=1 TO N
30 IF N/I=INT (N/I) THEN PRINT I;" ";
40 NEXT I</langsyntaxhighlight>
{{in}}
<pre>315</pre>
Line 1,226 ⟶ 1,758:
 
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<lang Tiny BASIC>100 PRINT "Give me a number:"
<syntaxhighlight lang="basic">100 PRINT "Give me a number:"
110 INPUT I
120 LET C=1
Line 1,233 ⟶ 1,766:
150 LET C=C+1
160 IF C<=I THEN GOTO 140
170 END</langsyntaxhighlight>
{{out}}
<pre>Give me a number:
Line 1,249 ⟶ 1,782:
20
30
60</pre>
</pre>
 
 
==={{header|True BASIC}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">SUB printfactors(n)
<lang qbasic>
IF n < 1 THEN EXIT SUB
sub printfactors(n)
ifPRINT n; < 1 then exit sub"=>";
printFOR n;i "=>"; 1 TO n / 2
IF REMAINDER(n, i) = 0 THEN PRINT i;
NEXT i
PRINT n
END SUB
 
CALL printfactors(11)
CALL printfactors(21)
CALL printfactors(32)
CALL printfactors(45)
CALL printfactors(67)
CALL printfactors(96)
END</syntaxhighlight>
 
==={{header|VBA}}===
<syntaxhighlight lang="vb">Function Factors(x As Integer) As String
Application.Volatile
Dim i As Integer
Dim cooresponding_factors As String
Factors = 1
corresponding_factors = x
For i = 2 To Sqr(x)
If x Mod i = 0 Then
Factors = Factors & ", " & i
If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors
End If
Next i
If x <> 1 Then Factors = Factors & ", " & corresponding_factors
End Function</syntaxhighlight>
{{out}}
<pre>cell formula is "=Factors(840)"
resultant value is "1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 15, 20, 21, 24, 28, 30, 35, 40, 42, 56, 60, 70, 84, 105, 120, 140, 168, 210, 280, 420, 840"</pre>
 
==={{header|XBasic}}===
{{trans|BASIC256}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Factors of an integer"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
DECLARE FUNCTION printFactors (n)
 
FUNCTION Entry ()
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
END FUNCTION
 
FUNCTION printFactors (n)
PRINT n; " =>";
FOR i = 1 TO n / 2
IF n MOD i = 0 THEN PRINT i; " ";
NEXT i
PRINT n
END FUNCTION
END PROGRAM</syntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">sub printFactors(n)
if n < 1 return 0
print n, " =>";
for i = 1 to n / 2
if remaindermod(n, i) = 0 then print i, " ";
next i
print n
end sub
 
printFactors(11)
call printfactors(11)
printFactors(21)
call printfactors(21)
printFactors(32)
call printfactors(32)
printFactors(45)
call printfactors(45)
printFactors(67)
call printfactors(67)
printFactors(96)
call printfactors(96)
print
end</syntaxhighlight>
end
 
</lang>
==={{header|ZX Spectrum Basic}}===
{{out}}
{{trans|AWK}}
<pre>
<syntaxhighlight lang="basic">10 INPUT "Enter a number or 0 to exit: ";n
Igual que la entrada de FreeBASIC.
20 IF n=0 THEN STOP
</pre>
30 PRINT "Factors of ";n;": ";
40 FOR i=1 TO n
50 IF FN m(n,i)=0 THEN PRINT i;" ";
60 NEXT i
70 DEF FN m(a,b)=a-INT (a/b)*b</syntaxhighlight>
 
=={{header|Batch File}}==
Command line version:
<langsyntaxhighlight lang="dos">@echo off
set res=Factors of %1:
for /L %%i in (1,1,%1) do call :fac %1 %%i
Line 1,289 ⟶ 1,889:
:fac
set /a test = %1 %% %2
if %test% equ 0 set res=%res% %2</langsyntaxhighlight>
 
{{out}}
Line 1,308 ⟶ 1,908:
 
Interactive version:
<langsyntaxhighlight lang="dos">@echo off
set /p limit=Gimme a number:
set res=Factors of %limit%:
Line 1,317 ⟶ 1,917:
:fac
set /a test = %1 %% %2
if %test% equ 0 set res=%res% %2</langsyntaxhighlight>
 
{{out}}
Line 1,327 ⟶ 1,927:
Gimme a number:102
Factors of 102: 1 2 3 6 17 34 51 102</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INSTALL @lib$+"SORTLIB"
sort% = FN_sortinit(0, 0)
PRINT "The factors of 45 are " FNfactorlist(45)
PRINT "The factors of 12345 are " FNfactorlist(12345)
END
DEF FNfactorlist(N%)
LOCAL C%, I%, L%(), L$
DIM L%(32)
FOR I% = 1 TO SQR(N%)
IF (N% MOD I% = 0) THEN
L%(C%) = I%
C% += 1
IF (N% <> I%^2) THEN
L%(C%) = (N% DIV I%)
C% += 1
ENDIF
ENDIF
NEXT I%
CALL sort%, L%(0)
FOR I% = 0 TO C%-1
L$ += STR$(L%(I%)) + ", "
NEXT
= LEFT$(LEFT$(L$))</lang>
 
{{out}}
<pre>The factors of 45 are 1, 3, 5, 9, 15, 45
The factors of 12345 are 1, 3, 5, 15, 823, 2469, 4115, 12345</pre>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">/* Calculate the factors of n and return their count.
* This function mutates the global array f[] which will
* contain all factors of n in ascending order after the call!
Line 1,404 ⟶ 1,972:
scale = o
return(l)
}</langsyntaxhighlight>
 
=={{header|Befunge}}==
<langsyntaxhighlight Befungelang="befunge">10:p&v: >:0:g%#v_0:g\:0:g/\v
>:0:g:*`| > >0:g1+0:p
>:0:g:*-#v_0:g\>$>:!#@_.v
> ^ ^ ," "<</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 1,416 ⟶ 1,984:
A bqncrate idiom.
 
<langsyntaxhighlight lang="bqn">Factors ← (1+↕)⊸(⊣/˜0=|)
 
•Show Factors 12345
•Show Factors 729</langsyntaxhighlight>
<syntaxhighlight lang="text">⟨ 1 3 5 15 823 2469 4115 12345 ⟩
⟨ 1 3 9 27 81 243 729 ⟩</langsyntaxhighlight>
 
The [https://github.com/mlochbaum/bqn-libs/blob/master/primes.bqn primes] library from bqn-libs can be used for a solution that's more efficient for large inputs. <code>FactorExponents</code> returns each unique prime factor along with its exponent.
<langsyntaxhighlight lang="bqn">⟨FactorExponents⟩ ← •Import "primes.bqn" # With appropriate path
Factors ← { ∧⥊ 1 ×⌜´ ⋆⟜(↕1+⊢)¨˝ FactorExponents 𝕩 }</langsyntaxhighlight>
 
=={{header|Burlesque}}==
<langsyntaxhighlight lang="burlesque">blsq ) 32767 fc
{1 7 31 151 217 1057 4681 32767}</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,499 ⟶ 2,067:
}
return 0;
}</langsyntaxhighlight>
===Prime factoring===
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,588 ⟶ 2,156:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,598 ⟶ 2,166:
=={{header|C sharp|C#}}==
===C# 1.0===
<langsyntaxhighlight lang="csharp">static void Main (string[] args) {
do {
Console.WriteLine ("Number:");
Line 1,618 ⟶ 2,186:
Console.WriteLine ("Done.");
} while (true);
}</langsyntaxhighlight>
{{out}}
<pre>Number:
32434243
For 1 through 5695
Found: 1. 32434243 / 1 = 32434243
Found: 307. 32434243 / 307 = 105649
Done.</pre>
 
===C# 3.0===
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,635 ⟶ 2,210:
Console.WriteLine (String.Join (", ", 45. Factors ()));
}
}</langsyntaxhighlight>
 
{{out}}
<pre>1, 3, 5, 9, 15, 45</pre>
<pre>Number:
32434243
For 1 through 5695
Found: 1. 32434243 / 1 = 32434243
Found: 307. 32434243 / 307 = 105649
Done.</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iomanip>
#include <vector>
Line 1,679 ⟶ 2,249:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 1,688 ⟶ 2,258:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
{Integer*} getFactors(Integer n) =>
(1..n).filter((Integer element) => element.divides(n));
Line 1,695 ⟶ 2,265:
print("the factors of ``i`` are ``getFactors(i)``");
}
}</langsyntaxhighlight>
 
=={{header|Chapel}}==
Inspired by the Clojure solution:
<langsyntaxhighlight lang="chapel">iter factors(n) {
for i in 1..floor(sqrt(n)):int {
if n % i == 0 then {
Line 1,706 ⟶ 2,276:
}
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn factors [n]
(filter #(zero? (rem n %)) (range 1 (inc n))))
 
(print (factors 45))</langsyntaxhighlight>
(1 3 5 9 15 45)
 
Improved version. Considers small factors from 1 up to (sqrt n) -- we increment it because range does not include the end point. Pair each small factor with its co-factor, flattening the results, and put them into a sorted set to get the factors in order.
<langsyntaxhighlight lang="lisp">(defn factors [n]
(into (sorted-set)
(mapcat (fn [x] [x (/ n x)])
(filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))) )))</langsyntaxhighlight>
 
Same idea, using for comprehensions.
<langsyntaxhighlight lang="lisp">(defn factors [n]
(into (sorted-set)
(reduce concat
(for [x (range 1 (inc (Math/sqrt n))) :when (zero? (rem n x))]
[x (/ n x)]))))</langsyntaxhighlight>
 
=={{header|CLU}}==
{{trans|Sather}}
<langsyntaxhighlight lang="clu">isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
Line 1,761 ⟶ 2,331:
stream$putl(po, "")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>Factors of 3135: 1 3 1045 5 627 11 285 15 209 19 165 33 95 55 57 3135
Line 1,771 ⟶ 2,341:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. FACTORS.
Line 1,812 ⟶ 2,382:
 
END PROGRAM FACTORS.
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript"># Reference implementation for finding factors is slow, but hopefully
# robust--we'll use it to verify the more complicated (but hopefully faster)
# algorithm.
Line 1,873 ⟶ 2,443:
console.log n, factors
if n < 1000000
verify_factors factors, n</langsyntaxhighlight>
 
{{out}}
Line 1,900 ⟶ 2,470:
=={{header|Common Lisp}}==
We iterate in the range <code>1..sqrt(n)</code> collecting ‘low’ factors and corresponding ‘high’ factors, and combine at the end to produce an ordered list of factors.
<langsyntaxhighlight lang="lisp">(defun factors (n &aux (lows '()) (highs '()))
(do ((limit (1+ (isqrt n))) (factor 1 (1+ factor)))
((= factor limit)
Line 1,909 ⟶ 2,479:
(when (zerop remainder)
(push factor lows)
(push quotient highs)))))</langsyntaxhighlight>
 
=={{header|Crystal}}==
{{trans|Ruby}}
Brute force and slow, by checking every value up to n.
<langsyntaxhighlight lang="ruby">struct Int
def factors() (1..self).select { |n| (self % n).zero? } end
end</langsyntaxhighlight>
 
Faster, by only checking values up to <math>\sqrt{n}</math>.
<langsyntaxhighlight lang="ruby">struct Int
def factors
f = [] of Int32
Line 1,927 ⟶ 2,497:
f.sort
end
end</langsyntaxhighlight>
 
'''Tests:'''
<langsyntaxhighlight lang="ruby">
[45, 53, 64].each {|n| puts "#{n} : #{n.factors}"}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,940 ⟶ 2,510:
=={{header|D}}==
===Procedural Style===
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.algorithm;
 
T[] factors(T)(in T n) pure nothrow {
Line 1,962 ⟶ 2,532:
void main() {
writefln("%(%s\n%)", [45, 53, 64, 1111111].map!factors);
}</langsyntaxhighlight>
{{out}}
<pre>[1, 3, 5, 9, 15, 45]
Line 1,970 ⟶ 2,540:
 
===Functional Style===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
auto factors(I)(I n) {
Line 1,978 ⟶ 2,548:
void main() {
36.factors.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4, 6, 9, 12, 18, 36]</pre>
Line 2,007 ⟶ 2,577:
=={{header|Dc}}==
=== Simple O(n) version ===
<syntaxhighlight lang="dc">
<lang dc>
[Enter positive number: ]P ? sn
[Factors of ]P lnn [ are: ]P
[q]sq 1si [[ ]P lin]sp [ li ln <q ln li % 0=p li1+si lxx ]dsxx AP
</syntaxhighlight>
</lang>
{{out}}
Factors of 998877 are: 1 3 11 33 30269 90807 332959 998877
0m1.120s
=== Faster O(sqrt(n)) version ===
<syntaxhighlight lang="dc">
<lang dc>
[Enter positive number: ]P ? sn
[Factors of ]P lnn [ are: ]P
Line 2,022 ⟶ 2,592:
[li lv <q ln li % 0=P li1+si lxx]dsxx
[lj 1>q lj1-sj Lbsi lpx lxx]dsxx AP
</syntaxhighlight>
</lang>
0m0.004s
=={{header|Delphi}}==
Line 2,028 ⟶ 2,598:
=={{header|Dyalect}}==
 
<langsyntaxhighlight Dyalectlang="dyalect">func Iterator.Where(pred) {
for x in this when pred(x) {
yield x
Line 2,040 ⟶ 2,610:
for x in 45.Factors() {
print(x)
}</langsyntaxhighlight>
 
Output:
Line 2,053 ⟶ 2,623:
=={{header|E}}==
{{improve|E|Use a cleverer algorithm such as in the Common Lisp example.}}
<langsyntaxhighlight lang="e">def factors(x :(int > 0)) {
var xfactors := []
for f ? (x % f <=> 0) in 1..x {
Line 2,059 ⟶ 2,629:
}
return xfactors
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">n = 720
for i = 1 to n
if n mod i = 0
Line 2,068 ⟶ 2,638:
.
.
print factors[]</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
'''prime-factors''' gives the list of n's prime-factors. We mix them to get all the factors.
<langsyntaxhighlight lang="scheme">
;; ppows
;; input : a list g of grouped prime factors ( 3 3 3 ..)
Line 2,091 ⟶ 2,661:
(for/fold (divs'(1)) ((g (map ppows (group (prime-factors n)))))
(for*/list ((a divs) (b g)) (* a b))))))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(lib 'bigint)
(factors 666)
Line 2,104 ⟶ 2,674:
(time ( length (factors huge)))
→ (394ms 7776)
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
Line 2,111 ⟶ 2,681:
2021-10-10 Integers are now read from the tape in decimal format, instead of being defined by the awkward method of pseudo-orders. The factorization of 999,999,999 has been removed, as it took too long on the commonly-used EdsacPC simulator (14.6 million orders - over 6 hours on the original EDSAC).
 
<langsyntaxhighlight lang="edsac">
[Factors of an integer, from Rosetta Code website.]
[EDSAC program, Initial Orders 2.]
Line 2,265 ⟶ 2,835:
E 4 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,292 ⟶ 2,862:
 
===Using higher-order function===
<langsyntaxhighlight lang="ela">open list
 
factors m = filter (\x -> m % x == 0) [1..m]</langsyntaxhighlight>
 
===Using comprehension===
<langsyntaxhighlight lang="ela">factors m = [x \\ x <- [1..m] | m % x == 0]</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def factor(1), do: [1]
def factor(n) do
Line 2,326 ⟶ 2,896:
IO.puts "#{name}\t prime count : #{value},\t#{time/1000000} sec"
end)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,338 ⟶ 2,908:
factor prime count : 1229, 7.316 sec
divisor prime count : 1229, 0.265 sec
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun factors = List by int n
List result = int[1]
for each int i in range(2, n)
if n % i == 0 do result.append(i) end
end
result.append(n)
return result
end
fun main = int by List args
int n = when(args.length == 0, ask(int, "Enter the number to factor please "), int!args[0])
writeLine(factors(n))
return 0
end
exit main(Runtime.args)
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\FactorsOfAnInteger.emal 999997
[1,757,1321,999997]
</pre>
 
=={{header|Erlang}}==
===with Built in fuctions===
<langsyntaxhighlight lang="erlang">factors(N) ->
[I || I <- lists:seq(1,trunc(N/2)), N rem I == 0]++[N].</langsyntaxhighlight>
 
===Recursive===
Another, less concise, but faster version
<langsyntaxhighlight lang="erlang">
 
-module(divs).
Line 2,366 ⟶ 2,959:
divisors(K,N,_Q) ->
[K, N div K] ++ divisors(K+1,N,math:sqrt(N)).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,382 ⟶ 2,975:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM FACTORS
 
Line 2,426 ⟶ 3,019:
PRINT("The factors of 12345 are ";L$)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,442 ⟶ 3,035:
 
{{Works with|Office 365 Betas 2021}}
<langsyntaxhighlight lang="lisp">=LAMBDA(n,
IF(1 < n,
LET(
Line 2,465 ⟶ 3,058:
IF(1 = n, {1}, NA())
)
)</langsyntaxhighlight>
 
and assuming that in the same worksheet, each of the following names is bound to the reusable generic lambda expression which follows it:
 
<langsyntaxhighlight lang="lisp">APPEND
=LAMBDA(xs,
LAMBDA(ys,
Line 2,527 ⟶ 3,120:
)
)
)</langsyntaxhighlight>
 
The '''FACTORS''' function, applied to an integer, defines a column of integer values.
Line 2,717 ⟶ 3,310:
 
Also, this is lazily evaluated.
<langsyntaxhighlight lang="fsharp">let factors number = seq {
for divisor in 1 .. (float >> sqrt >> int) number do
if number % divisor = 0 then
yield divisor
if number <> 1 then yield number / divisor //special case condition: when number=1 then divisor=(number/divisor), so don't repeat it
}</langsyntaxhighlight>
 
===Prime factoring===
<langsyntaxhighlight lang="fsharp">
[6;120;2048;402642;1206432] |> Seq.iter(fun n->printf "%d :" n; [1..n]|>Seq.filter(fun g->n%g=0)|>Seq.iter(fun n->printf " %d" n); printfn "");;</langsyntaxhighlight>
 
{{out}}
Line 2,746 ⟶ 3,339:
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[1[\$@$@-][\$@$@$@$@\/*=[$." "]?1+]#.%]f:
45f;! 53f;! 64f;!</langsyntaxhighlight>
 
=={{header|Fish}}==
<syntaxhighlight lang="fish">0v
<lang Fish>0v
>i:0(?v'0'%+a*
>~a,:1:>r{% ?vr:nr','ov
^:&:;?(&:+1r:< <
</syntaxhighlight>
</lang>
Must be called with pre-polulated value (Positive Integer) in the input stack. Try at Fish Playground[https://fishlanguage.com/playground/onD7KN6YK3XMzLFdr].
For Input Number : <pre> 120</pre>
Line 2,762 ⟶ 3,355:
=={{header|Forth}}==
This is a slightly optimized algorithm, since it realizes there are no factors between n/2 and n. The values are saved on the stack and - in true Forth fashion - printed in descending order.
<langsyntaxhighlight Forthlang="forth">: factors dup 2/ 1+ 1 do dup i mod 0= if i swap then loop ;
: .factors factors begin dup dup . 1 <> while drop repeat drop cr ;
 
Line 2,768 ⟶ 3,361:
53 .factors
64 .factors
100 .factors</langsyntaxhighlight>
=== 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.
<syntaxhighlight lang="forth">
<lang FORTH>
: sq s" dup *" evaluate ; immediate
 
Line 2,799 ⟶ 3,392:
0 :noname swap . ; <with-factors> (.factors)
: .factors (.factors) drop ;
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,812 ⟶ 3,405:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Factors
implicit none
integer :: i, number
Line 2,831 ⟶ 3,424:
end if
end program</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
Sub printFactors(n As Integer)
If n < 1 Then Return
Print n; " =>";
For i As Integer = 1 To n / 2
If n Mod i = 0 Then Print i; " ";
Next i
Print n
End Sub
 
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
<pre>
11 => 1 11
21 => 1 3 7 21
32 => 1 2 4 8 16 32
45 => 1 3 5 9 15 45
67 => 1 67
96 => 1 2 3 4 6 8 12 16 24 32 48 96
</pre>
 
=={{header|Frink}}==
Line 2,874 ⟶ 3,435:
The following produces all factors of n, including 1 and n:
 
<syntaxhighlight lang ="frink">allFactors[n]</langsyntaxhighlight>
 
=={{header|FunL}}==
Function to compute set of factors:
<langsyntaxhighlight lang="funl">def factors( n ) = {d | d <- 1..n if d|n}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="funl">for x <- [103, 316, 519, 639, 760]
println( 'The set of factors of ' + x + ' is ' + factors(x) )</langsyntaxhighlight>
{{out}}
Line 2,892 ⟶ 3,453:
The set of factors of 639 is {9, 639, 71, 213, 1, 3}
The set of factors of 760 is {8, 19, 4, 40, 152, 5, 10, 76, 1, 95, 190, 760, 20, 2, 38, 380}
</pre>
 
=={{header|FutureBasic}}==
<lang futurebasic>
include "ConsoleWindow"
 
clear local mode
local fn IntegerFactors( f as long ) as Str255
dim as long i, s, l(100), c : c = 0
dim as Str255 factorStr
 
for i = 1 to sqr(f)
if ( f mod i == 0 )
l(c) = i
c++
if ( f <> i ^ 2 )
l(c) = ( f / i )
c++
end if
end if
next i
s = 1
while ( s = 1 )
s = 0
for i = 0 to c-1
if l(i) > l(i+1) and l(i+1) <> 0
swap l(i), l(i+1)
s = 1
end if
next i
wend
for i = 0 to c-1
if ( i < c -1 )
factorStr = factorStr + str$(l(i)) + ","
else
factorStr = factorStr + str$(l(i))
end if
next
end fn = factorStr
 
print "Factors of 25 are:"; fn IntegerFactors( 25 )
print "Factors of 45 are:"; fn IntegerFactors( 45 )
print "Factors of 103 are:"; fn IntegerFactors( 103 )
print "Factors of 760 are:"; fn IntegerFactors( 760 )
print "Factors of 12345 are:"; fn IntegerFactors( 12345 )
print "Factors of 32766 are:"; fn IntegerFactors( 32766 )
print "Factors of 32767 are:"; fn IntegerFactors( 32767 )
print "Factors of 57097 are:"; fn IntegerFactors( 57097 )
print "Factors of 12345678 are:"; fn IntegerFactors( 12345678 )
print "Factors of 32434243 are:"; fn IntegerFactors( 32434243 )
</lang>
 
Output:
<pre>
Factors of 25 are: 1, 5, 25
Factors of 45 are: 1, 3, 5, 9, 15, 45
Factors of 103 are: 1, 103
Factors of 760 are: 1, 2, 4, 5, 8, 10, 19, 20, 38, 40, 76, 95, 152, 190, 380, 760
Factors of 12345 are: 1, 3, 5, 15, 823, 2469, 4115, 12345
Factors of 32766 are: 1, 2, 3, 6, 43, 86, 127, 129, 254, 258, 381, 762, 5461, 10922, 16383, 32766
Factors of 32767 are: 1, 7, 31, 151, 217, 1057, 4681, 32767
Factors of 57097 are: 1, 57097
Factors of 12345678 are: 1, 2, 3, 6, 9, 18, 47, 94, 141, 282, 423, 846, 14593, 29186, 43779, 87558, 131337, 262674, 685871, 1371742, 2057613, 4115226, 6172839, 12345678
Factors of 32434243 are: 1, 307, 105649, 32434243
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in function
DivisorsInt(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]
Line 2,978 ⟶ 3,475:
 
div2(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]</langsyntaxhighlight>
 
=={{header|Go}}==
Trial division, no prime number generator, but with some optimizations. It's good enough to factor any 64 bit integer, with large primes taking several seconds.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,033 ⟶ 3,530:
fmt.Println(fs)
fmt.Println("Number of factors =", len(fs))
}</langsyntaxhighlight>
 
{{out}}
Line 3,065 ⟶ 3,562:
 
=={{header|Gosu}}==
<langsyntaxhighlight lang="gosu">var numbers = {11, 21, 32, 45, 67, 96}
numbers.each(\ number -> printFactors(number))
 
Line 3,073 ⟶ 3,570:
(1 .. n/2).each(\ i -> {result += n % i == 0 ? "${i} " : ""})
print("${result}${n}")
}</langsyntaxhighlight>
 
{{out}}
Line 3,087 ⟶ 3,584:
=={{header|Groovy}}==
A straight brute force approach up to the square root of ''N'':
<langsyntaxhighlight lang="groovy">def factorize = { long target ->
 
if (target == 1) return [1L]
Line 3,099 ⟶ 3,596:
[1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">((1..30) + [333333]).each { println ([number:it, factors:factorize(it)]) }</langsyntaxhighlight>
{{out}}
<pre>[number:1, factors:[1]]
Line 3,138 ⟶ 3,635:
=={{header|Haskell}}==
Using [https://web.archive.org/web/20121130222921/http://www.polyomino.f2s.com/david/haskell/codeindex.html D. Amos'es Primes module] for finding prime factors
<langsyntaxhighlight Haskelllang="haskell">import HFM.Primes (primePowerFactors)
import Control.Monad (mapM)
import Data.List (product)
Line 3,145 ⟶ 3,642:
 
factors = map product .
mapM (\(p,m)-> [p^i | i<-[0..m]]) . primePowerFactors</langsyntaxhighlight>
 
Returns list of factors out of order, e.g.:
 
<Langsyntaxhighlight lang="haskell">~> factors 42
[1,7,3,21,2,14,6,42]</langsyntaxhighlight>
 
Or, [[Prime_decomposition#Haskell|prime decomposition task]] can be used (although, a trial division-only version will become very slow for large primes),
 
<langsyntaxhighlight lang="haskell">import Data.List (group)
primePowerFactors = map (\x-> (head x, length x)) . group . factorize</langsyntaxhighlight>
 
The above function can also be found in the package [http://hackage.haskell.org/package/arithmoi <code>arithmoi</code>], as <code>Math.NumberTheory.Primes.factorise :: Integer -> [(Integer, Int)]</code>, [http://hackage.haskell.org/package/arithmoi-0.4.2.0/docs/Math-NumberTheory-Primes-Factorisation.html which performs] "factorisation of Integers by the elliptic curve algorithm after Montgomery" and "is best suited for numbers of up to 50-60 digits".
Line 3,161 ⟶ 3,658:
Or, deriving cofactors from factors up to the square root:
 
<langsyntaxhighlight Haskelllang="haskell">integerFactors :: Int -> [Int]
integerFactors n
| 1 > n = []
| otherwise = lows ++ fmap<> (quot n) (<$> part n (reverse lows))
where
part n
Line 3,170 ⟶ 3,667:
| otherwise = id
(square, lows) =
(,) . (^ 2) <*> (filter ((0 ==) . rem n) . enumFromTo 1) $
floor <*> (sqrtfilter $((0 fromIntegral==) . rem n) . enumFromTo 1)
$ floor (sqrt $ fromIntegral n)
 
main :: IO ()
main = print $ integerFactors 600</langsyntaxhighlight>
{{Out}}
<pre>[1,2,3,4,5,6,8,10,12,15,20,24,25,30,40,50,60,75,100,120,150,200,300,600]</pre>
Line 3,180 ⟶ 3,678:
=== List comprehension ===
Naive, functional, no import, in increasing order:
<langsyntaxhighlight Haskelllang="haskell">factorsNaive n =
[ i
| i <- [1 .. n]
, mod n i == 0 ]</langsyntaxhighlight>
<langsyntaxhighlight Haskelllang="haskell">~> factorsNaive 25
[1,5,25]</langsyntaxhighlight>
 
Factor, ''cofactor''. Get the list of factor&ndash;cofactor pairs sorted, for a quadratic speedup:
<langsyntaxhighlight Haskelllang="haskell">import Data.List (sort)
 
factorsCo n =
Line 3,198 ⟶ 3,696:
i :
[ d
| d > i ] ]</langsyntaxhighlight>
 
A version of the above without the need for sorting, making it to be ''online'' (i.e. productive immediately, which can be seen in GHCi); factors in increasing order:
<langsyntaxhighlight Haskelllang="haskell">factorsO n =
ds ++
[ r
Line 3,215 ⟶ 3,713:
[ i
| i <- [1 .. r - 1]
, mod n i == 0 ]</langsyntaxhighlight>
Testing:
<langsyntaxhighlight Haskelllang="haskell">*Main> :set +s
~> factorsO 120
[1,2,3,4,5,6,8,10,12,15,20,24,30,40,60,120]
Line 3,225 ⟶ 3,723:
[1,7,41,287,541,3787,22181,77551,155267,542857,3179591,22257137,41955091,2936856
37,1720158731,12041111117]
(0.09 secs, 50758224 bytes)</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest"> DLG(NameEdit=N, TItle='Enter an integer')
 
DO i = 1, N^0.5
Line 3,234 ⟶ 3,732:
ENDDO
 
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
numbers := arglist ||| [ 32767, 45, 53, 64, 100] # combine command line provided and default set of values
every writes(lf,"factors of ",i := !numbers,"=") & writes(divisors(i)," ") do lf := "\n"
end
 
link factors</langsyntaxhighlight>
 
{{out}}
Line 3,252 ⟶ 3,750:
 
{{libheader|Icon Programming Library}} [http://www.cs.arizona.edu/icon/library/src/procs/factors.icn divisors]
 
=={{Header|Insitux}}==
 
{{Trans|Clojure}}
 
<syntaxhighlight lang="insitux">
(function factors n
(filter (div? n) (range 1 (inc n))))
 
(factors 45)
</syntaxhighlight>
 
{{out}}
 
<pre>
[1 3 5 9 15 45]
</pre>
 
=={{header|J}}==
The "brute force" approach is the most concise:
 
<langsyntaxhighlight Jlang="j">foi=: [: I. 0 = (|~ i.@>:)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> foi 40
1 2 4 5 8 10 20 40</langsyntaxhighlight>
 
Basically we test every non-negative integer up through the number itself to see if it divides evenly.
Line 3,268 ⟶ 3,783:
 
J has a primitive, q: which returns its argument's prime factors.
<langsyntaxhighlight Jlang="j">q: 40
2 2 2 5</langsyntaxhighlight>
 
Alternatively, q: can produce provide a table of the exponents of the unique relevant prime factors
<langsyntaxhighlight Jlang="j"> __ q: 420
2 3 5 7
2 1 1 1</langsyntaxhighlight>
 
With this, we can form lists of each of the potential relevant powers of each of these prime factors
<langsyntaxhighlight Jlang="j"> (^ i.@>:)&.>/ __ q: 420
┌─────┬───┬───┬───┐
│1 2 4│1 3│1 5│1 7│
└─────┴───┴───┴───┘</langsyntaxhighlight>
 
From here, it's a simple matter (<code>*/&>@{</code> or, find all possible combinations of one item from each list (<code>{</code> without a left argument) then unpack each list and multiply its elements) to compute all possible factors of the original number
<langsyntaxhighlight Jlang="j">factrs=: */&>@{@((^ i.@>:)&.>/)@q:~&__
factrs 40
1 5
2 10
4 20
8 40</langsyntaxhighlight>
 
However, a data structure which is organized around the prime decomposition of the argument can be hard to read. So, for reader convenience, we should probably arrange them in a monotonically increasing list:
 
<langsyntaxhighlight Jlang="j"> factorsfactrst=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
factorsfactrst 420
1 2 3 4 5 6 7 10 12 14 15 20 21 28 30 35 42 60 70 84 105 140 210 420</langsyntaxhighlight>
 
A less efficient, but concise variation on this theme:
 
<langsyntaxhighlight Jlang="j"> ~.,*/&> { 1 ,&.> q: 40
1 5 2 10 4 20 8 40</langsyntaxhighlight>
 
This computes 2^n intermediate values where n is the number of prime factors of the original number.
Line 3,305 ⟶ 3,820:
That said, note that we get a representation issue when dealing with large numbers:
 
<langsyntaxhighlight Jlang="j"> factors 568474220
1 2 4 5 10 17 20 34 68 85 170 340 1.67198e6 3.34397e6 6.68793e6 8.35992e6 1.67198e7 2.84237e7 3.34397e7 5.68474e7 1.13695e8 1.42119e8 2.84237e8 5.68474e8</langsyntaxhighlight>
 
One approach here (if we don't want to explicitly format the result) is to use an arbitrary precision (aka "extended") argument. This propagates through into the result:
 
<langsyntaxhighlight Jlang="j"> factors 568474220x
1 2 4 5 10 17 20 34 68 85 170 340 1671983 3343966 6687932 8359915 16719830 28423711 33439660 56847422 113694844 142118555 284237110 568474220</langsyntaxhighlight>
 
Another less efficient approach, in which remainders are examined up to the square root, larger factors obtained as fractions, and the combined list nubbed and sorted might be:
<langsyntaxhighlight Jlang="j">factorsOfNumber=: monad define
Y=. y"_
/:~ ~. ( , Y%]) ( #~ 0=]|Y) 1+i.>.%:y
Line 3,320 ⟶ 3,835:
 
factorsOfNumber 40
1 2 4 5 8 10 20 40</langsyntaxhighlight>
 
Another approach:
 
<langsyntaxhighlight Jlang="j">odometer =: #: i.@(*/)
factors=: (*/@:^"1 odometer@:>:)/@q:~&__</langsyntaxhighlight>
 
See also the J essays [[j:Essays/Odometer|Odometer]] and [[j:Essays/Divisors|Divisors]].
See http://www.jsoftware.com/jwiki/Essays/Odometer
 
=={{header|Java}}==
{{works with|Java|5+}}
<langsyntaxhighlight lang="java5">public static TreeSet<Long> factors(long n)
{
TreeSet<Long> factors = new TreeSet<Long>();
Line 3,343 ⟶ 3,858:
}
return factors;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,349 ⟶ 3,864:
===Imperative===
 
<langsyntaxhighlight lang="javascript">function factors(num)
{
var
Line 3,368 ⟶ 3,883:
factors(45); // [1,3,5,9,15,45]
factors(53); // [1,53]
factors(64); // [1,2,4,8,16,32,64]</langsyntaxhighlight>
 
===Functional===
Line 3,376 ⟶ 3,891:
Translating the naive list comprehension example from Haskell, using a list monad for the comprehension
 
<langsyntaxhighlight JavaScriptlang="javascript">// Monadic bind (chain) for lists
function chain(xs, f) {
return [].concat.apply([], xs.map(f));
Line 3,394 ⟶ 3,909:
}
 
factors_naive(6)</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight JavaScriptlang="javascript">[1, 2, 3, 6]</langsyntaxhighlight>
 
Translating the Haskell (lows and highs) example
 
<langsyntaxhighlight JavaScriptlang="javascript">console.log(
(function (lstTest) {
 
Line 3,459 ⟶ 3,974:
 
})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767])
);</langsyntaxhighlight>
 
Output:
 
<langsyntaxhighlight JavaScriptlang="javascript">integerFactors(n)
 
25 --> 1 5 25
Line 3,475 ⟶ 3,990:
32766 --> 1 2 3 6 43 86 127 129 254 258 381 762 5461 10922 16383 32766
32767 --> 1 7 31 151 217 1057 4681 32767
</syntaxhighlight>
</lang>
 
 
====ES6====
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (lstTest) {
'use strict';
 
Line 3,552 ⟶ 4,067:
) + '\n';
 
})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767]);</langsyntaxhighlight>
 
{{Out}}
Line 3,572 ⟶ 4,087:
=={{header|jq}}==
{{Works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># This implementation uses "sort" for tidiness
def factors:
. as $num
Line 3,587 ⟶ 4,102:
(45, 53, 64) | "\(.): \(factors)" ;
 
task</langsyntaxhighlight>
{{Out}}
$ jq -n -M -r -c -f factors.jq
Line 3,595 ⟶ 4,110:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
""" Return the factors of n, including 1, n """
function factors(n)
function factors(n::T)::Vector{T} where T <: Integer
f = [one(n)]
sort(vec(map(prod, Iterators.product((p.^(0:m) for (p,e m) in factoreachfactor(n))...))))
f = reduce(vcat, [f*p^j for j in 1:e], init=f)
end
return length(f) == 1 ? [one(n), n] : sort!(f)
end
 
Line 3,610 ⟶ 4,122:
@time println("The factors of $n are: $(factors(n))")
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,619 ⟶ 4,131:
The factors of 53 are: [1, 53]
0.000102 seconds (35 allocations: 1.516 KiB)
 
 
The factors of 64 are: [1, 2, 4, 8, 16, 32, 64]
0.000093 seconds (56 allocations: 3.172 KiB)
Line 3,640 ⟶ 4,154:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> f:{i:{y[&x=y*x div y]}[x;1+!_sqrt x];?i,x div|i}
equivalent to:
q)f:{i:{y where x=y*x div y}[x ; 1+ til floor sqrt x]; distinct i,x div reverse i}
Line 3,658 ⟶ 4,172:
/ Number of factors for 3491888400 .. 3491888409
#:'f' 3491888400+!10
1920 16 4 4 12 16 32 16 8 24</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun printFactors(n: Int) {
if (n < 1) return
print("$n => ")
Line 3,673 ⟶ 4,187:
val numbers = intArrayOf(11, 21, 32, 45, 67, 96)
for (number in numbers) printFactors(number)
}</langsyntaxhighlight>
 
{{out}}
Line 3,686 ⟶ 4,200:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def factors
{def factors.r
Line 3,710 ⟶ 4,224:
-> 1 2 4 8 16 32 64
 
</syntaxhighlight>
</lang>
 
=={{header|LFE}}==
Line 3,717 ⟶ 4,231:
 
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):
<langsyntaxhighlight lang="lisp">
(defun factors (n)
(list-comp
((<- i (when (== 0 (rem n i))) (lists:seq 1 (trunc (/ n 2)))))
i))
</syntaxhighlight>
</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):
<langsyntaxhighlight lang="lisp">
(defun factors (n)
"Tail-recursive prime factors function."
Line 3,740 ⟶ 4,254:
((n k acc)
(factors n (+ k 1) acc)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,746 ⟶ 4,260:
> (factors 10677106534462215678539721403561279)
(104729 104729 104729 98731 98731 32579 29269 1)
</pre>
 
=={{header|Liberty BASIC}}==
<lang lb>num = 10677106534462215678539721403561279
maxnFactors = 1000
dim primeFactors(maxnFactors), nPrimeFactors(maxnFactors)
global nDifferentPrimeNumbersFound, nFactors, iFactor
 
 
print "Start finding all factors of ";num; ":"
 
nDifferentPrimeNumbersFound=0
dummy = factorize(num,2)
nFactors = showPrimeFactors(num)
dim factors(nFactors)
dummy = generateFactors(1,1)
sort factors(), 0, nFactors-1
for i=1 to nFactors
print i;" ";factors(i-1)
next i
 
print "done"
 
wait
 
 
function factorize(iNum,offset)
factorFound=0
i = offset
do
if (iNum MOD i)=0 _
then
if primeFactors(nDifferentPrimeNumbersFound) = i _
then
nPrimeFactors(nDifferentPrimeNumbersFound) = nPrimeFactors(nDifferentPrimeNumbersFound) + 1
else
nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1
primeFactors(nDifferentPrimeNumbersFound) = i
nPrimeFactors(nDifferentPrimeNumbersFound) = 1
end if
if iNum/i<>1 then dummy = factorize(iNum/i,i)
factorFound=1
end if
i=i+1
loop while factorFound=0 and i<=sqr(iNum)
if factorFound=0 _
then
nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1
primeFactors(nDifferentPrimeNumbersFound) = iNum
nPrimeFactors(nDifferentPrimeNumbersFound) = 1
end if
end function
 
 
function showPrimeFactors(iNum)
showPrimeFactors=1
print iNum;" = ";
for i=1 to nDifferentPrimeNumbersFound
print primeFactors(i);"^";nPrimeFactors(i);
if i<nDifferentPrimeNumbersFound then print " * "; else print ""
showPrimeFactors = showPrimeFactors*(nPrimeFactors(i)+1)
next i
end function
 
 
function generateFactors(product,pIndex)
if pIndex>nDifferentPrimeNumbersFound _
then
factors(iFactor) = product
iFactor=iFactor+1
else
for i=0 to nPrimeFactors(pIndex)
dummy = generateFactors(product*primeFactors(pIndex)^i,pIndex+1)
next i
end if
end function</lang>
 
{{out}}
<lang lb>Start finding all factors of 10677106534462215678539721403561279:
10677106534462215678539721403561279 = 29269^1 * 32579^1 * 98731^2 * 104729^3
1 1
2 29269
3 32579
4 98731
5 104729
6 953554751
7 2889757639
8 3065313101
9 3216557249
10 3411966091
11 9747810361
12 10339998899
13 10968163441
14 94145414120981
15 99864835517479
16 285308661456109
17 302641427774831
18 317573913751019
19 321027175754629
20 336866824130521
21 357331796744339
22 1020878431297169
23 1082897744693371
24 1148684789012489
25 9295070881578575111
26 9859755075476219149
27 10458744358910058191
28 29880090805636839461
29 31695334089430275799
30 33259198413230468851
31 33620855089606540541
32 35279725624365333809
33 37423001741237879131
34 106915577231321212201
35 113410797903992051459
36 973463478356842592799919
37 1032602289299548955255621
38 1095333837964291484285239
39 3129312029983540559911069
40 3319420643851943354153471
41 3483202590619213772296379
42 3694810384914157044482761
43 11197161487859039232598529
44 101949856624833767901342716951
45 108143405156052462534965931709
46 327729719588146219298926345301
47 364792324112959639158827476291
48 10677106534462215678539721403561279
done</lang>
 
===A Simpler Approach===
This is a somewhat simpler approach for finding the factors of smaller numbers (less than one million).
 
<lang lb>
print "ROSETTA CODE - Factors of an integer"
'A simpler approach for smaller numbers
[Start]
print
input "Enter an integer (< 1,000,000): "; n
n=abs(int(n)): if n=0 then goto [Quit]
if n>999999 then goto [Start]
FactorCount=FactorCount(n)
select case FactorCount
case 1: print "The factor of 1 is: 1"
case else
print "The "; FactorCount; " factors of "; n; " are: ";
for x=1 to FactorCount
print " "; Factor(x);
next x
if FactorCount=2 then print " (Prime)" else print
end select
goto [Start]
 
[Quit]
print "Program complete."
end
 
function FactorCount(n)
dim Factor(100)
for y=1 to n
if y>sqr(n) and FactorCount=1 then
'If no second factor is found by the square root of n, then n is prime.
FactorCount=2: Factor(FactorCount)=n: exit function
end if
if (n mod y)=0 then
FactorCount=FactorCount+1
Factor(FactorCount)=y
end if
next y
end function
</lang>
 
{{out}}
<pre>
ROSETTA CODE - Factors of an integer
 
Enter an integer (< 1,000,000): 1
The factor of 1 is: 1
 
Enter an integer (< 1,000,000): 2
The 2 factors of 2 are: 1 2 (Prime)
 
Enter an integer (< 1,000,000): 4
The 3 factors of 4 are: 1 2 4
 
Enter an integer (< 1,000,000): 6
The 4 factors of 6 are: 1 2 3 6
 
Enter an integer (< 1,000,000): 999999
The 64 factors of 999999 are: 1 3 7 9 11 13 21 27 33 37 39 63 77 91 99 111 117 143 189 231 259 273 297 333 351 407 429 481 693 777 819 999 1001 1221 1287 1443 2079 2331 2457 2849 3003 3367 3663 3861 4329 5291 6993 8547 9009 10101 10989 129
87 15873 25641 27027 30303 37037 47619 76923 90909 111111 142857 333333 999999
 
Enter an integer (< 1,000,000):
Program complete.
</pre>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on factors(n)
res = [1]
repeat with i = 2 to n/2
Line 3,950 ⟶ 4,270:
res.add(n)
return res
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">put factors(45)
-- [1, 3, 5, 9, 15, 45]
put factors(53)
-- [1, 53]
put factors(64)
-- [1, 2, 4, 8, 16, 32, 64]</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to factors :n
output filter [equal? 0 modulo :n ?] iseq 1 :n
end
 
show factors 28 ; [1 2 4 7 14 28]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Factors( n )
local f = {}
Line 3,977 ⟶ 4,297:
return f
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
\\ Factors of an integer
\\ For act as BASIC's FOR (if N<1 no loop start)
Line 4,005 ⟶ 4,325:
CALL LikeM2000
 
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
 
<syntaxhighlight lang="maple">
<lang Maple>
numtheory:-divisors(n);
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Factorize[n_Integer] := Divisors[n]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> function fact(n);
f = factor(n); % prime decomposition
K = dec2bin(0:2^length(f)-1)-'0'; % generate all possible permutations
Line 4,028 ⟶ 4,348:
disp(F);
end;
</langsyntaxhighlight>
 
{{out}}
Line 4,048 ⟶ 4,368:
=={{header|Maxima}}==
The builtin <code>divisors</code> function does this.
<langsyntaxhighlight lang="maxima">(%i96) divisors(100);
(%o96) {1,2,4,5,10,20,25,50,100}</langsyntaxhighlight>
 
Such a function could be implemented like so:
<langsyntaxhighlight lang="maxima">divisors2(n) := map( lambda([l], lreduce("*", l)),
apply( cartesian_product,
map( lambda([fac],
setify(makelist(fac[1]^i, i, 0, fac[2]))),
ifactors(n))));</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
fn factors n =
(
return (for i = 1 to n+1 where mod n i == 0 collect i)
)
</syntaxhighlight>
</lang>
 
{{out}}
<syntaxhighlight lang="maxscript">
<lang MAXScript>
factors 3
#(1, 3)
Line 4,078 ⟶ 4,398:
factors 54
#(1, 2, 3, 6, 9, 18, 27, 54)
</syntaxhighlight>
</lang>
 
=={{header|Mercury}}==
Line 4,095 ⟶ 4,415:
 
===fac.m===
<langsyntaxhighlight Mercurylang="mercury">:- module fac.
 
:- interface.
Line 4,134 ⟶ 4,454:
factor(N) = Factors :- factor(N, Factors).
 
:- end_module fac.</langsyntaxhighlight>
 
===Use and output===
Line 4,146 ⟶ 4,466:
=={{header|min}}==
{{works with|min|0.19.6}}
<langsyntaxhighlight lang="min">(mod 0 ==) :divisor?
(() 0 shorten) :new
(new (over swons 'pred dip) pick times nip) :iota
Line 4,161 ⟶ 4,481:
24 factors puts!
9 factors puts!
11 factors puts!</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">factors = function(n)
result = [1]
for i in range(2, n)
Line 4,176 ⟶ 4,496:
if n <= 0 then break
print factors(n)
end while</langsyntaxhighlight>
{{out}}
<pre>Number to factor (0 to quit)? 42
Line 4,195 ⟶ 4,515:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">factors(num) New fctr,list,sep,sqrt
If num<1 Quit "Too small a number"
If num["." Quit "Not an integer"
Line 4,205 ⟶ 4,525:
w $$factors(45) ; [1,3,5,9,15,45]
w $$factors(53) ; [1,53]
w $$factors(64) ; [1,2,4,8,16,32,64]</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">n = int(input())
 
for i in range(1, n / 2)
Line 4,215 ⟶ 4,535:
end
end
println n</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx ***********************************************************
* 21.04.2013 Walter Pachl
* 21.04.2013 add method main to accept argument(s)
Line 4,253 ⟶ 4,573:
If j*j=x Then /*for a square number as input */
lo=lo j /* add its square root */
return lo hi /* return both lists */</langsyntaxhighlight>
 
{{out}}
Line 4,269 ⟶ 4,589:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import intsets, math, algorithm
proc factors(n: int): seq[int] =
Line 4,282 ⟶ 4,602:
result.sort()
echo factors(45)</langsyntaxhighlight>
 
=={{header|Niue}}==
<langsyntaxhighlight Niuelang="niue">[ 'n ; [ negative-or-zero [ , ] if
[ n not-factor [ , ] when ] else ] n times n ] 'factors ;
 
Line 4,295 ⟶ 4,615:
53 factors .s .clr ( => 1 53 ) newline
64 factors .s .clr ( => 1 2 4 8 16 32 64 ) newline
12 factors .s .clr ( => 1 2 3 4 6 12 ) </langsyntaxhighlight>
 
=={{header|Oberon-2}}==
Oxford Oberon-2
<langsyntaxhighlight lang="oberon2">
MODULE Factors;
IMPORT Out,SYSTEM;
Line 4,365 ⟶ 4,685:
Out.Int(v.len,6);Out.String(" factors");Out.Ln
END Factors.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,376 ⟶ 4,696:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
use Structure;
 
Line 4,413 ⟶ 4,733:
}
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec range = function 0 -> [] | n -> range(n-1) @ [n]
 
let factors n =
List.filter (fun v -> (n mod v) = 0) (range n)</langsyntaxhighlight>
 
=={{header|Odin}}==
Uses built-in dynamic arrays, and only checks up to the square root
<syntaxhighlight lang="odin">
package main
 
import "core:fmt"
import "core:slice"
 
factors :: proc(n: int) -> [dynamic]int {
d := 1
factors := make([dynamic]int)
 
for {
q := n / d
r := n % d
 
if d >= q {
if d == q && r == 0 {
append(&factors, d)
}
slice.sort(factors[:])
return factors
}
if r == 0 {
append(&factors, d, q)
}
 
d += 1
}
}
 
main :: proc() {
for n in ([?]int{100, 108, 999, 255, 256, 257}) {
a := factors(n)
fmt.println("The factors of", n, "are", a)
delete(a)
}
}
</syntaxhighlight>
{{Out}}
<pre>
The factors of 100 are [1, 2, 4, 5, 10, 20, 25, 50, 100]
The factors of 108 are [1, 2, 3, 4, 6, 9, 12, 18, 27, 36, 54, 108]
The factors of 999 are [1, 3, 9, 27, 37, 111, 333, 999]
The factors of 255 are [1, 3, 5, 15, 17, 51, 85, 255]
The factors of 256 are [1, 2, 4, 8, 16, 32, 64, 128, 256]
The factors of 257 are [1, 257]
</pre>
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">Integer method: factors self seq filter(#[ self isMultiple ]) ;
 
120 factors println</langsyntaxhighlight>
 
{{out}}
Line 4,433 ⟶ 4,801:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {Factors N}
Sqr = {Float.toInt {Sqrt {Int.toFloat N}}}
Line 4,452 ⟶ 4,820:
end
in
{Show {Factors 53}}</langsyntaxhighlight>
 
=={{header|Panda}}==
Panda has a factor function already, it's defined as:
<langsyntaxhighlight lang="panda">fun factor(n) type integer->integer
f where n.mod(1..n=>f)==0
 
45.factor</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">divisors(n)</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{trans|Fortran}}
{{works with|Free Pascal|2.6.2}}
<langsyntaxhighlight lang="pascal">program Factors;
var
i, number: integer;
Line 4,485 ⟶ 4,853:
write(i, number/i);
writeln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,501 ⟶ 4,869:
"runtime overhead" +25% instead +100% for quicksort against no sort.<BR>
Especially fast for consecutive integers.
<langsyntaxhighlight lang="pascal">program FacOfInt;
// gets factors of consecutive integers fast
// limited to 1.2e11
Line 4,979 ⟶ 5,347:
AllFacsOut(Divs,true);
AllFacsOut(Divs,false);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 5,004 ⟶ 5,372:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub factors
{
my($n) = @_;
return grep { $n % $_ == 0 }(1 .. $n);
}
print join ' ',factors(64), "\n";</langsyntaxhighlight>
 
Or more intelligently:
 
<langsyntaxhighlight lang="perl">sub factors {
my $n = shift;
$n = -$n if $n < 0;
Line 5,023 ⟶ 5,391:
@divisors, map { $_*$_ == $n ? () : int($n/$_) } reverse @divisors;
}
print join " ", factors(64), "\n";</langsyntaxhighlight>
 
One could also use a module, e.g.:
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/divisors/;
print join " ", divisors(12345678), "\n";
# Alternately something like: fordivisors { say } 12345678; </langsyntaxhighlight>
 
=={{header|Phix}}==
There is a builtin factors(n), which takes an optional second parameter to include 1 and n:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">12345</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
{1,3,5,15,823,2469,4115,12345}
</pre>
You can find the implementation of factors(), prime_factors(), and prime_factorsprime_powers() in builtins\pfactors.e,<br>
and mpz_factors(), mpz_prime_factors(), and mpz_pollard_rho() in mpfr.e for larger numbers, for example:
<div style="font-size: 11px">
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- [p2js/integer() bugs]</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3491888400</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"factors"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {2,3,4,5,"...",698377680,872972100,1163962800.0,1745944200.0," (1,918 factors)"}</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3491888400</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"factors"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {2,3,4,5,"...",698377680,872972100,1163962800.0,1745944200.0," (1,918 factors)"}
-- If the include1 parameter is 1 or "BOTH", then you'll also get 1 and 3491888400</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">prime_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3491888400</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {2,3,5,7,11,13,17,19}</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">prime_powers</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3491888400</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- <nowiki>{{</nowiki>2,4},{3,3},{5,2},{7,1},{11,1},{13,1},{17,1},{19,1<nowiki>}}</nowiki></span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_prime_factors</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"3491888400"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {2,3,5,7,11,13,17,19}</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">mpz_prime_factors</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"3491888400"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- <nowiki>{{</nowiki>2,4},{3,3},{5,2},{7,1},{11,1},{13,1},{17,1},{19,1<nowiki>}}</nowiki>
-- Note that mpz_prime_factors() only accepts string or mpz, and not a raw native atom/integer.</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">108233175859200</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- 666</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">108233175859200</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- 666</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"10677106534462215678539721403561279"</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">mpz_prime_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- <nowiki>{{</nowiki>29269,1},{32579,1},{98731,2},{104729,3<nowiki>}}</nowiki></span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"factors"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {1,29269,"...","364792324112959639158827476291","10677106534462215678539721403561279"," (48 factors)"}</span>
<!--</syntaxhighlight>-->
</div>
Note the value in (string) d exceeds the precision limit of an IEEE-754 float, and would trigger a suitable human readable run-time error if passed to any of the non-mpz routines. Sadly, 1200034005600070000008900000000000000000 exceeds the capabilities of my mpz_pollard_rho(), which I had hoped to showcase - perhaps you would like to improve it?
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Factors_of_an_integer
by Galileo, 05/2022 #/
 
Line 5,059 ⟶ 5,448:
96 factors
 
pstack</langsyntaxhighlight>
{{out}}
<pre>
Line 5,067 ⟶ 5,456:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">function GetFactors($n){
$factors = array(1, $n);
for($i = 2; $i * $i <= $n; $i++){
Line 5,078 ⟶ 5,467:
sort($factors);
return $factors;
}</langsyntaxhighlight>
 
=={{header|Picat}}==
===List comprehension===
<langsyntaxhighlight Picatlang="picat">factors(N) = [[D,N // D] : D in 1..N.sqrt.floor, N mod D == 0].flatten.sort_remove_dups.</langsyntaxhighlight>
 
===Recursion===
{{trans|Prolog}}
<langsyntaxhighlight Picatlang="picat">factors2(N,Fs) :-
integer(N),
N > 0,
Line 5,095 ⟶ 5,484:
between(1,L,X),
0 == N mod X,
( F = X ; F = N // X ).</langsyntaxhighlight>
 
===Loop using set===
<langsyntaxhighlight Picatlang="picat">factors3(N) = Set.keys.sort =>
Set = new_set(),
Set.put(1),
Line 5,105 ⟶ 5,494:
Set.put(I),
Set.put(N//I)
end.</langsyntaxhighlight>
 
===Comparison===
Let's compare with 18! (6402373705728000) which has 14688 factors. The recursive version is slightly faster than the loop + set version.
<langsyntaxhighlight Picatlang="picat">go =>
N = 6402373705728000, % factorial(18),
println("factors:"),
Line 5,117 ⟶ 5,506:
println("factors3:"),
time(Fs3=factors3(N)).len),
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,134 ⟶ 5,523:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de factors (N)
(filter
'((D) (=0 (% N D)))
(range 1 N) ) )</langsyntaxhighlight>
 
=={{header|PILOT}}==
<langsyntaxhighlight lang="pilot">T :Enter a number.
A :#n
C :factor = 1
Line 5,151 ⟶ 5,540:
J :*Loop
*Finished
END:</langsyntaxhighlight>
 
=={{header|PL/0}}==
{{trans|GW-BASIC}}
PL/0 does not handle strings. So, no prompt. The program waits for entering a number, and then displays the factors.
<syntaxhighlight lang="pascal">
var n, absn, ndiv2, i;
begin
? n;
absn := n;
if n < 0 then absn := -n;
ndiv2 := absn / 2;
i := 1;
while i <= ndiv2 do
begin
if (absn / i) * i = absn then ! i;
i := i + 1
end;
! absn;
end.
</syntaxhighlight>
4 runs.
{{in}}
<pre>1</pre>
{{out}}
<pre>
1
</pre>
{{in}}
<pre>11</pre>
{{out}}
<pre>
1
2
3
4
6
12
</pre>
{{in}}
<pre>13</pre>
{{out}}
<pre>
1
13
</pre>
{{in}}
<pre>-22222</pre>
{{out}}
<pre>
1
2
41
82
271
542
11111
22222
</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">factors: procedure options(main);
declare i binary( 15 )fixed;
declare n binary( 15 )fixed;
Line 5,164 ⟶ 5,611:
end;
end factors;
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,188 ⟶ 5,635:
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Show the factors of 11.
Line 5,209 ⟶ 5,656:
To show a factor and another factor:
If the factor is not the other factor, write "" then the factor then " " then the other factor then " " on the console without advancing; exit.
Write "" then the factor on the console without advancing.</langsyntaxhighlight>
{{out}}
<pre>
Line 5,226 ⟶ 5,673:
The PL/I include file "pg.inc" can be found on the [[Polyglot:PL/I and PL/M]] page.
Note the use of text in column 81 onwards to hide the PL/I specifics from the PL/M compiler.
<langsyntaxhighlight lang="pli">factors_100H: procedure options (main);
 
/* PL/I DEFINITIONS */
Line 5,268 ⟶ 5,715:
CALL PRNL;
END;
EOF: end factors_100H;</langsyntaxhighlight>
{{out}}
<pre>
Line 5,286 ⟶ 5,733:
=={{header|PowerShell}}==
===Straightforward but slow===
<langsyntaxhighlight lang="powershell">function Get-Factor ($a) {
1..$a | Where-Object { $a % $_ -eq 0 }
}</langsyntaxhighlight>
This one uses a range of integers up to the target number and just filters it using the <code>Where-Object</code> cmdlet. It's very slow though, so it is not very usable for larger numbers.
===A little more clever===
<langsyntaxhighlight lang="powershell">function Get-Factor ($a) {
1..[Math]::Sqrt($a) `
| Where-Object { $a % $_ -eq 0 } `
| ForEach-Object { $_; $a / $_ } `
| Sort-Object -Unique
}</langsyntaxhighlight>
Here the range of integers is only taken up to the square root of the number, the same filtering applies. Afterwards the corresponding larger factors are calculated and sent down the pipeline along with the small ones found earlier.
 
=={{header|ProDOS}}==
Uses the math module:
<langsyntaxhighlight ProDOSlang="prodos">editvar /newvar /value=a /userinput=1 /title=Enter an integer:
do /delimspaces %% -a- >b
printline Factors of -a-: -b- </langsyntaxhighlight>
 
=={{header|Prolog}}==
 
'''Simple Brute Force Implementation'''
<syntaxhighlight lang="prolog">
<lang Prolog>
brute_force_factors( N , Fs ) :-
integer(N) ,
Line 5,314 ⟶ 5,761:
setof( F , ( between(1,N,F) , N mod F =:= 0 ) , Fs )
.
</syntaxhighlight>
</lang>
 
'''A Slightly Smarter Implementation'''
<syntaxhighlight lang="prolog">
<lang Prolog>
smart_factors(N,Fs) :-
integer(N) ,
Line 5,330 ⟶ 5,777:
( F = X ; F is N // X )
.
</syntaxhighlight>
</lang>
 
Not every Prolog has <code>between/3</code>: you might need this:
 
<syntaxhighlight lang="prolog">
<lang Prolog>
 
between(X,Y,Z) :-
Line 5,351 ⟶ 5,798:
between1(X1,Y,Z)
.
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,382 ⟶ 5,829:
N = 32767, Factors = [1, 7, 31, 151, 217, 1057, 4681, 32767] ;
N = 32767, Factors = [1, 7, 31, 151, 217, 1057, 4681, 32767] .
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>Procedure PrintFactors(n)
Protected i, lim=Round(sqr(n),#PB_Round_Up)
NewList F.i()
For i=1 To lim
If n%i=0
AddElement(F()): F()=i
AddElement(F()): F()=n/i
EndIf
Next
;- Present the result
SortList(F(),#PB_Sort_Ascending)
ForEach F()
Print(str(F())+" ")
Next
EndProcedure
 
If OpenConsole()
Print("Enter integer to factorize: ")
PrintFactors(Val(Input()))
Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input()
EndIf</lang>
 
{{out}}
<pre>
Enter integer to factorize: 96
1 2 3 4 6 8 12 16 24 32 48 96
</pre>
 
=={{header|Python}}==
Naive and slow but simplest (check all numbers from 1 to n):
<langsyntaxhighlight lang="python">>>> def factors(n):
return [i for i in range(1, n + 1) if not n%i]</langsyntaxhighlight>
 
Slightly better (realize that there are no factors between n/2 and n):
<langsyntaxhighlight lang="python">>>> def factors(n):
return [i for i in range(1, n//2 + 1) if not n%i] + [n]
 
>>> factors(45)
[1, 3, 5, 9, 15, 45]</langsyntaxhighlight>
 
Much better (realize that factors come in pairs, the smaller of which is no bigger than sqrt(n)):
<syntaxhighlight lang ="python">>>> from math import sqrtisqrt
>>> def factor(n):
factors1, factorsfactors2 = set()[], []
for x in range(1, int(sqrtisqrt(n)) + 1):
if n % x == 0:
factors factors1.addappend(x)
factors factors2.addappend(n // x)
x += 1
return sorted(factors)
if x * x == n:
 
factors1.append(x)
>>> for i in (45, 53, 64): print( "%i: factors: %s" % (i, factor(i)) )
factors1.extend(reversed(factors2))
return factors1
 
for i in 45, 53, 64:
print("%i: factors: %s" % (i, factor(i)))</syntaxhighlight><pre>
45: factors: [1, 3, 5, 9, 15, 45]
53: factors: [1, 53]
64: factors: [1, 2, 4, 8, 16, 32, 64]</langpre>
 
More efficient when factoring many numbers:
<langsyntaxhighlight lang="python">from itertools import chain, cycle, accumulate # last of which is Python 3 only
 
def factors(n):
Line 5,459 ⟶ 5,881:
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r</langsyntaxhighlight>
 
 
=={{header|Quackery}}==
 
<code>isqrtsqrt+</code> is defined at [[Isqrt (integer square root) of X#Quackery]]. It returns the integer square root and remainder (i.e. the square root of 11 is 3 remainder 2, because three squared plus two equals eleven.) If the number is a perfect square the remainder is zero. This is used to remove a duplicate factor from the list of factors which is generated when finding the factors of a perfect square.
 
The nest editing at the end of the definition (i.e. the code after the <code>drop</code> on a line by itself) removes a duplicate factor if there is one, and arranges the factors in ascending numerical order at the same time.
 
<syntaxhighlight lang="text"> [ 1[] swap
[dup 2dupsqrt+ <0 not= whiledip
2 << again ]
0
[ over 1 > while
dip [ 2 >> 2dup - ]
dup 1 >> unrot -
dup 0 < iff drop
else
[ 2swap nip
rot over + ]
again ] nip swap ] is isqrt ( n --> n n )
 
[ [] swap
dup isqrt 0 = dip
[ times
[ dup i^ 1+ /mod iff
Line 5,488 ⟶ 5,896:
rot join
i^ 1+ join swap ]
drop
dup size 2 / split ]
if [ -1 split drop ]
swap join ] is factors ( n --> [ )
Line 5,500 ⟶ 5,908:
factors witheach
[ echo i if say ", " ]
cr ]</langsyntaxhighlight>
 
{{out}}
Line 5,528 ⟶ 5,936:
=={{header|R}}==
===Array solution===
<langsyntaxhighlight lang="rsplus">factors <- function(n)
{
if(length(n) > 1)
Line 5,538 ⟶ 5,946:
one.to.n[(n %% one.to.n) == 0]
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,553 ⟶ 5,961:
===Filter solution===
With identical output, a more idiomatic way is to use R's Filter.
<langsyntaxhighlight lang="rsplus">factors <- function(n) c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n)
#Vectorize is an interesting alternative to the previous solution's lapply.
manyFactors <- function(vec) Vectorize(factors)(vec)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 5,589 ⟶ 5,997:
(time (length (divisors huge)))
;; And this one clocks at 17ms
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>sub factors (Int $n) { (1..$n).grep($n %% *) }</langsyntaxhighlight>
 
=={{header|REALbasic}}==
<lang vb>Function factors(num As UInt64) As UInt64()
'This function accepts an unsigned 64 bit integer as input and returns an array of unsigned 64 bit integers
Dim result() As UInt64
Dim iFactor As UInt64 = 1
While iFactor <= num/2 'Since a factor will never be larger than half of the number
If num Mod iFactor = 0 Then
result.Append(iFactor)
End If
iFactor = iFactor + 1
Wend
result.Append(num) 'Since a given number is always a factor of itself
Return result
End Function</lang>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
 
factors: function [n [integer!]] [
Line 5,635 ⟶ 6,028:
][
print mold/flat sort factors num
]</langsyntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Factors 120>>;
}
 
Factors {
s.N = <Factors (s.N 1)>;
(s.N s.D), <Compare s.N <* s.D s.D>>: '-' = ;
(s.N s.D), <Divmod s.N s.D>: {
(s.D) 0 = s.D;
(s.F) 0 = s.D <Factors (s.N <+ 1 s.D>)> s.F;
(s.X) s.Y = <Factors (s.N <+ 1 s.D>)>;
};
};</syntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120</pre>
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
<lang Relation>
program factors(num)
relation fact
Line 5,652 ⟶ 6,062:
print
end program
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Line 5,665 ⟶ 6,075:
 
This REXX version is about &nbsp; '''22%''' &nbsp; faster than the alternate REXX version &nbsp; (2<sup>nd</sup> version).
<langsyntaxhighlight lang="rexx">/*REXX program displays divisors of any [negative/zero/positive] integer or a range.*/
parse arg LO HI inc . /*obtain the optional args*/
HI= word(HI LO 20, 1); LO= word(LO 1,1); inc= word(inc 1,1) /*define the range options*/
Line 5,693 ⟶ 6,103:
end /*j*/ /* [↑] % ≡ integer division. ___*/
if sq.j==x then return a j b /*Was X a square? Then insert √ x */
return a b /*return the divisors of both lists. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> -6 &nbsp; 200 </tt>}}
 
Line 5,913 ⟶ 6,323:
===Alternate Version===
{{trans|REXX optimized version}}
<langsyntaxhighlight REXXlang="rexx">/* REXX ***************************************************************
* Program to calculate and show divisors of positive integer(s).
* 03.08.2012 Walter Pachl simplified the above somewhat
Line 5,944 ⟶ 6,354:
If j*j=x Then /*for a square number as input */
lo=lo j /* add its square root */
return lo hi /* return both lists */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
 
Line 6,152 ⟶ 6,562:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nArray = list(100)
n = 45
Line 6,164 ⟶ 6,574:
see "" + nArray[i] + " "
next
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ → n
≪ { } DUP 1 n √ '''FOR''' d
'''IF''' n d MOD NOT
'''THEN'''
d + n d /
'''IF''' DUP d ≠ '''THEN''' ROT + SWAP '''ELSE''' DROP '''END'''
'''END'''
'''NEXT'''
SWAP +
≫ ≫
'FACTS' STO
 
45 FACTS
53 FACTS
64 FACTS
{{out}}
<pre>
3: { 1 3 5 9 15 45 }
2: { 1 53 }
1: { 1 2 4 8 16 32 64 }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Integer
def factors() (1..self).select { |n| (self % n).zero? } end
end
p 45.factors</langsyntaxhighlight>
[1, 3, 5, 9, 15, 45]
 
As we only have to loop up to <math>\sqrt{n}</math>, we can write
<langsyntaxhighlight lang="ruby">class Integer
def factors
1.upto(Integer.sqrt(self)).select {|i| (self % i).zero?}.inject([]) do |f, i|
Line 6,182 ⟶ 6,616:
end
end
[45, 53, 64].each {|n| puts "#{n} : #{n.factors}"}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,190 ⟶ 6,624:
 
===Using the prime library===
<langsyntaxhighlight lang="ruby">
require 'prime'
 
Line 6,203 ⟶ 6,637:
 
[1, 7, 45, 100].each{|n| p factors n}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 6,211 ⟶ 6,645:
[1, 2, 4, 5, 10, 20, 25, 50, 100]
</pre>
 
=={{header|Run BASIC}}==
<lang runbasic>PRINT "Factors of 45 are ";factorlist$(45)
PRINT "Factors of 12345 are "; factorlist$(12345)
END
function factorlist$(f)
DIM L(100)
FOR i = 1 TO SQR(f)
IF (f MOD i) = 0 THEN
L(c) = i
c = c + 1
IF (f <> i^2) THEN
L(c) = (f / i)
c = c + 1
END IF
END IF
NEXT i
s = 1
while s = 1
s = 0
for i = 0 to c-1
if L(i) > L(i+1) and L(i+1) <> 0 then
t = L(i)
L(i) = L(i+1)
L(i+1) = t
s = 1
end if
next i
wend
FOR i = 0 TO c-1
factorlist$ = factorlist$ + STR$(L(i)) + ", "
NEXT
end function</lang>
 
{{out}}
<pre>Factors of 45 are 1, 3, 5, 9, 15, 45,
Factors of 12345 are 1, 3, 5, 15, 823, 2469, 4115, 12345, </pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
 
<lang rust>fn main() {
assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100)); // asserts that two expressions are equal to each other
assert_eq!(vec![1, 101], factor(101));
Line 6,269 ⟶ 6,664:
factors.sort(); // sorts the factors into numerical order for viewing purposes
factors // returns the factors
}</langsyntaxhighlight>
 
Alternative functional version:
 
<langsyntaxhighlight lang="rust">
fn factor(n: i32) -> Vec<i32> {
(1..=n).filter(|i| n % i == 0).collect()
}
</syntaxhighlight>
</lang>
 
=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
 
<lang sather>class MAIN is
 
factors!(n :INT):INT is
Line 6,307 ⟶ 6,701:
end;
end;
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
Brute force approach:
<langsyntaxhighlight Scalalang="scala">def factors(num: Int) = {
(1 to num).filter { divisor =>
num % divisor == 0
}
}</langsyntaxhighlight>
Brute force until sqrt(num) is enough, the code above can be edited as follows (Scala 3 enabled)
<langsyntaxhighlight Scalalang="scala">def factors(num: Int) = {
val list = (1 to math.sqrt(num).floor.toInt).filter(num % _ == 0)
list ++ list.reverse.dropWhile(d => d*d == num).map(num / _)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
This implementation uses a naive trial division algorithm.
<langsyntaxhighlight lang="scheme">(define (factors n)
(define (*factors d)
(cond ((> d n) (list))
Line 6,332 ⟶ 6,726:
 
(display (factors 1111111))
(newline)</langsyntaxhighlight>
 
{{out}}
Line 6,340 ⟶ 6,734:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: writeFactors (in integer: number) is func
Line 6,369 ⟶ 6,763:
writeFactors(number);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 6,382 ⟶ 6,776:
 
A simple brute force method using an indexed partial function as a filter.
<langsyntaxhighlight lang="sequencel">Factors(num(0))[i] := i when num mod i = 0 foreach i within 1 ... num;</langsyntaxhighlight>
 
'''Slightly More Efficient Method'''
 
A slightly more efficient method, only going up to the sqrt(n).
<langsyntaxhighlight lang="sequencel">Factors(num(0)) :=
let
factorPairs[i] :=
Line 6,395 ⟶ 6,789:
foreach i within 1 ... floor(sqrt(num));
in
join(factorPairs);</langsyntaxhighlight>
 
=={{header|Sidef}}==
Built-in:
<langsyntaxhighlight lang="ruby">say divisors(97) #=> [1, 97]
say divisors(2695) #=> [1, 5, 7, 11, 35, 49, 55, 77, 245, 385, 539, 2695]</langsyntaxhighlight>
 
Trial-division (slow for large n):
 
<langsyntaxhighlight lang="ruby">func divisors(n) {
gather {
{ |d|
Line 6,414 ⟶ 6,808:
[53, 64, 32766].each {|n|
say "divisors(#{n}): #{divisors(n)}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,423 ⟶ 6,817:
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">n@(Integer traits) primeFactors
[
[| :result |
result nextPut: 1.
n primesDo: [| :prime | result nextPut: prime]] writingAs: {}
].</langsyntaxhighlight>
where <tt>primesDo:</tt> is a part of the standard numerics library:
<langsyntaxhighlight lang="slate">n@(Integer traits) primesDo: block
"Decomposes the Integer into primes, applying the block to each (in increasing
order)."
Line 6,444 ⟶ 6,838:
[div: next.
next: next + 2] "Just looks at the next odd integer."
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
Copied from the Python example, but code added to the Integer built in class:
<syntaxhighlight lang="smalltalk">Integer>>factors
 
<lang smalltalk>Integer>>factors
| a |
a := OrderedCollection new.
Line 6,456 ⟶ 6,848:
((self \\ i) = 0) ifTrue: [ a add: i ] ].
a add: self.
^a</langsyntaxhighlight>
 
Then use as follows:
 
<langsyntaxhighlight lang="smalltalk">
59 factors -> an OrderedCollection(1 59)
120 factors -> an OrderedCollection(1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120)
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
Need to print the list because Standard ML truncates the display of
longer returned lists.
<langsyntaxhighlight Standardlang="standard MLml">fun printIntList ls =
(
List.app (fn n => print(Int.toString n ^ " ")) ls;
Line 6,486 ⟶ 6,878:
factors'(n,1)
end;
</syntaxhighlight>
</lang>
Call:
<langsyntaxhighlight Standardlang="standard MLml">printIntList(factors 12345)
printIntList(factors 120)</langsyntaxhighlight>
{{out}}
<pre>1 3 5 15 823 2469 4115 12345
Line 6,497 ⟶ 6,889:
=={{header|Swift}}==
Simple implementation:
<langsyntaxhighlight Swiftlang="swift">func factors(n: Int) -> [Int] {
return filter(1...n) { n % $0 == 0 }
}</langsyntaxhighlight>
More efficient implementation:
<langsyntaxhighlight Swiftlang="swift">import func Darwin.sqrt
 
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
Line 6,519 ⟶ 6,911:
return sorted(result)
}</langsyntaxhighlight>
Call:
<langsyntaxhighlight Swiftlang="swift">println(factors(4))
println(factors(1))
println(factors(25))
println(factors(63))
println(factors(19))
println(factors(768))</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 4]
Line 6,537 ⟶ 6,929:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
[1..351 -> \(when <?(351 mod $ <=0>)> do $! \)] -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,546 ⟶ 6,938:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc factors {n} {
set factors {}
for {set i 1} {$i <= sqrt($n)} {incr i} {
Line 6,557 ⟶ 6,949:
puts [factors 64]
puts [factors 45]
puts [factors 53]</langsyntaxhighlight>
 
{{out}}
Line 6,567 ⟶ 6,959:
This should work in all Bourne-compatible shells, assuming the system has both <tt>sort</tt> and at least one of <tt>bc</tt> or <tt>dc</tt>.
 
<syntaxhighlight lang="text">factor() {
r=`echo "sqrt($1)" | bc` # or `echo $1 v p | dc`
i=1
Line 6,578 ⟶ 6,970:
done | sort -nu
}
</syntaxhighlight>
</lang>
 
=={{header|Ursa}}==
This program takes an integer from the command line and outputs its factors.
<langsyntaxhighlight lang="ursa">decl int n
set n (int args<1>)
 
Line 6,591 ⟶ 6,983:
end if
end for
out n endl console</langsyntaxhighlight>
 
=={{header|Ursala}}==
The simple way:
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
factors "n" = (filter not remainder/"n") nrange(1,"n")</langsyntaxhighlight>
The complicated way:
<langsyntaxhighlight Ursalalang="ursala">factors "n" = nleq-<&@s <.~&r,quotient>*= "n"-* (not remainder/"n")*~ nrange(1,root("n",2))</langsyntaxhighlight>
Another idea would be to approximate an upper bound for the square root of <code>"n"</code> with some bit twiddling such as <code>&!*K31 "n"</code>, which evaluates to a binary number of all 1's half the width of "n" rounded up, and another would be to use the <code>division</code> function to get the quotient and remainder at the same time. Combining these ideas, losing the dummy variable, and cleaning up some other cruft, we have
<langsyntaxhighlight Ursalalang="ursala">factors = nleq-<&@rrZPFLs+ ^(~&r,division)^*D/~& nrange/1+ &!*K31</langsyntaxhighlight>
where <code>nleq-<&</code> isn't strictly necessary unless an ordered list is required.
<langsyntaxhighlight Ursalalang="ursala">#cast %nL
 
example = factors 100</langsyntaxhighlight>
 
{{out}}
<pre><1,2,4,5,10,20,25,50,100></pre>
 
=={{header|VBA}}==
<lang vb>Function Factors(x As Integer) As String
Application.Volatile
Dim i As Integer
Dim cooresponding_factors As String
Factors = 1
corresponding_factors = x
For i = 2 To Sqr(x)
If x Mod i = 0 Then
Factors = Factors & ", " & i
If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors
End If
Next i
If x <> 1 Then Factors = Factors & ", " & corresponding_factors
End Function</lang>
{{out}}
<pre>cell formula is "=Factors(840)"
resultant value is "1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 15, 20, 21, 24, 28, 30, 35, 40, 42, 56, 60, 70, 84, 105, 120, 140, 168, 210, 280, 420, 840"</pre>
 
 
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">
<lang Verilog>
module main;
integer i, n;
Line 6,645 ⟶ 7,017:
end
endmodule
</syntaxhighlight>
</lang>
{{out}}
<pre>
45 => 1 3 5 9 15 45
</pre>
 
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
factors1 &n !-\%%n @to n
factors_tacit @(\\%% !- @to)
Line 6,661 ⟶ 7,032:
!factors1 720
]]
}</langsyntaxhighlight>
Returns: <pre>[
[1 2 5 10]
Line 6,667 ⟶ 7,038:
[1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 30 36 40 45 48 60 72 80 90 120 144 180 240 360 720]
]</pre>
 
=={{header|V (Vlang)}}==
{{trans|Ring}}
<syntaxhighlight lang="Zig">
fn main() {
mut arr := []int{len: 100}
mut n, mut j := 45, 0
for i in 1..n + 1 {
if n % i == 0 {
j++
arr[j] = i
}
}
print("Factors of ${n} = ")
for i in 1..j + 1 {print(" ${arr[i]} ")}
}
</syntaxhighlight>
 
{{out}}
<pre>
Factors of 45 = 1 3 5 9 15 45
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./math" for Int
 
var a = [11, 21, 32, 45, 67, 96, 159, 723, 1024, 5673, 12345, 32767, 123459, 999997]
System.print("The factors of the following numbers are:")
for (e in a) SystemFmt.print("%(Fmt.d(6$6d => $n", e)), => %(Int.divisors(e))")</langsyntaxhighlight>
{{out}}
<pre>
Line 6,698 ⟶ 7,091:
=={{header|X86 Assembly}}==
{{works with|nasm}}
<langsyntaxhighlight lang="asm">
section .bss
factorArr resd 250 ;big buffer against seg fault
Line 6,731 ⟶ 7,124:
mov esp, ebp ;garbage collecting
ret
</syntaxhighlight>
</lang>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int N0, N, F;
[N0:= 1;
Line 6,750 ⟶ 7,143:
N0:= N0+1;
until KeyHit;
]</langsyntaxhighlight>
 
{{out}}
Line 6,786 ⟶ 7,179:
57097 = 57097
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<lang yabasic>
sub printFactors(n)
if n < 1 then return 0 : fi
print n, " =>",
for i = 1 to n / 2
if mod(n, i) = 0 then print i, " "; : fi
next i
print n
end sub
 
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
print
end
</lang>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
 
=={{header|zkl}}==
{{trans|Chapel}}
<langsyntaxhighlight lang="zkl">fcn f(n){ (1).pump(n.toFloat().sqrt(), List,
'wrap(m){((n % m)==0) and T(m,n/m) or Void.Skip}) }
fcn g(n){ [[(m); [1..n.toFloat().sqrt()],'{n%m==0}; '{T(m,n/m)} ]] } // list comprehension</langsyntaxhighlight>
{{out}}
<pre>
Line 6,827 ⟶ 7,193:
L(L(1,45),L(3,15),L(5,9))
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<lang zxbasic>10 INPUT "Enter a number or 0 to exit: ";n
20 IF n=0 THEN STOP
30 PRINT "Factors of ";n;": ";
40 FOR i=1 TO n
50 IF FN m(n,i)=0 THEN PRINT i;" ";
60 NEXT i
70 DEF FN m(a,b)=a-INT (a/b)*b</lang>
2,093

edits