Factors of an integer: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 29: | Line 29: | ||
=={{header|0815}}== |
=={{header|0815}}== |
||
< |
<syntaxhighlight lang="0815"> |
||
<:1:~>|~#:end:>~x}:str:/={^:wei:~%x<:a:x=$~ |
<:1:~>|~#:end:>~x}:str:/={^:wei:~%x<:a:x=$~ |
||
=}:wei:x<:1:+{>~>x=-#:fin:^:str:}:fin:{{~% |
=}:wei:x<:1:+{>~>x=-#:fin:^:str:}:fin:{{~% |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F factor(n) |
||
V factors = Set[Int]() |
V factors = Set[Int]() |
||
L(x) 1..Int(sqrt(n)) |
L(x) 1..Int(sqrt(n)) |
||
Line 46: | Line 46: | ||
L(i) (45, 53, 64) |
L(i) (45, 53, 64) |
||
print(i‘: factors: ’String(factor(i)))</ |
print(i‘: factors: ’String(factor(i)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 57: | Line 57: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
Very compact version. |
Very compact version. |
||
< |
<syntaxhighlight lang="360asm">* Factors of an integer - 07/10/2015 |
||
FACTOR CSECT |
FACTOR CSECT |
||
USING FACTOR,R15 set base register |
USING FACTOR,R15 set base register |
||
Line 79: | Line 79: | ||
PG DC CL132' ' buffer |
PG DC CL132' ' buffer |
||
YREGS |
YREGS |
||
END FACTOR</ |
END FACTOR</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 86: | Line 86: | ||
=={{header|68000 Assembly}}== |
=={{header|68000 Assembly}}== |
||
< |
<syntaxhighlight lang="68000devpac">;max input range equals 0 to 0xFFFFFFFF. |
||
Line 113: | Line 113: | ||
;end of program</ |
;end of program</syntaxhighlight> |
||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program factorst64.s */ |
/* program factorst64.s */ |
||
Line 291: | Line 291: | ||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun factors-r (n i) |
||
(declare (xargs :measure (nfix (- n i)))) |
(declare (xargs :measure (nfix (- n i)))) |
||
(cond ((zp (- n i)) |
(cond ((zp (- n i)) |
||
Line 303: | Line 303: | ||
(defun factors (n) |
(defun factors (n) |
||
(factors-r n 1))</ |
(factors-r n 1))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC PrintFactors(CARD a) |
||
BYTE notFirst |
BYTE notFirst |
||
CARD p |
CARD p |
||
Line 338: | Line 338: | ||
Test(6502) |
Test(6502) |
||
Test(12345) |
Test(12345) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Factors_of_an_integer.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Factors_of_an_integer.png Screenshot from Atari 8-bit computer] |
||
Line 352: | Line 352: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">function factor(n:uint):Vector.<uint> |
||
{ |
{ |
||
var factors:Vector.<uint> = new Vector.<uint>(); |
var factors:Vector.<uint> = new Vector.<uint>(); |
||
Line 358: | Line 358: | ||
if(n % i == 0)factors.push(i); |
if(n % i == 0)factors.push(i); |
||
return factors; |
return factors; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
with Ada.Command_Line; |
with Ada.Command_Line; |
||
procedure Factors is |
procedure Factors is |
||
Line 382: | Line 382: | ||
end loop; |
end loop; |
||
Ada.Text_IO.Put_Line (Positive'Image (Number) & "."); |
Ada.Text_IO.Put_Line (Positive'Image (Number) & "."); |
||
end Factors;</ |
end Factors;</syntaxhighlight> |
||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
< |
<syntaxhighlight lang="aikido">import math |
||
function factor (n:int) { |
function factor (n:int) { |
||
Line 418: | Line 418: | ||
printvec (factor (45)) |
printvec (factor (45)) |
||
printvec (factor (25)) |
printvec (factor (25)) |
||
printvec (factor (100))</ |
printvec (factor (100))</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 428: | Line 428: | ||
Note: The following implements generators, eliminating the need of declaring arbitrarily long '''int''' arrays for caching. |
Note: The following implements generators, eliminating the need of declaring arbitrarily long '''int''' arrays for caching. |
||
< |
<syntaxhighlight lang="algol68">MODE YIELDINT = PROC(INT)VOID; |
||
PROC gen factors = (INT n, YIELDINT yield)VOID: ( |
PROC gen factors = (INT n, YIELDINT yield)VOID: ( |
||
Line 452: | Line 452: | ||
# OD # )); |
# OD # )); |
||
print(new line) |
print(new line) |
||
OD</ |
OD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 461: | Line 461: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% return the factors of n ( n should be >= 1 ) in the array factor % |
% 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) % |
% the bounds of factor should be 0 :: len (len must be at least 1) % |
||
Line 512: | Line 512: | ||
for i := 1 until 100 do testFactorsOf( i ) |
for i := 1 until 100 do testFactorsOf( i ) |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 529: | Line 529: | ||
=={{header|ALGOL-M}}== |
=={{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.) |
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.) |
||
< |
<syntaxhighlight lang="algol"> |
||
BEGIN |
BEGIN |
||
Line 580: | Line 580: | ||
DONE: WRITE ("GOODBYE"); |
DONE: WRITE ("GOODBYE"); |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>NUMBER TO FACTOR (OR 0 TO QUIT): |
<pre>NUMBER TO FACTOR (OR 0 TO QUIT): |
||
Line 599: | Line 599: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl"> factors←{(0=(⍳⍵)|⍵)/⍳⍵} |
||
factors 12345 |
factors 12345 |
||
1 3 5 15 823 2469 4115 12345 |
1 3 5 15 823 2469 4115 12345 |
||
factors 720 |
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</ |
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</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
===Functional=== |
===Functional=== |
||
{{Trans|JavaScript}} |
{{Trans|JavaScript}} |
||
< |
<syntaxhighlight lang="applescript">-- integerFactors :: Int -> [Int] |
||
on integerFactors(n) |
on integerFactors(n) |
||
if n = 1 then |
if n = 1 then |
||
Line 702: | Line 702: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="applescript">{1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120}</syntaxhighlight> |
||
---- |
---- |
||
===Straightforward=== |
===Straightforward=== |
||
< |
<syntaxhighlight lang="applescript">on factors(n) |
||
set output to {} |
set output to {} |
||
Line 728: | Line 728: | ||
end factors |
end factors |
||
factors(123456789)</ |
factors(123456789)</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
< |
<syntaxhighlight lang="applescript">{1, 3, 9, 3607, 3803, 10821, 11409, 32463, 34227, 13717421, 41152263, 123456789}</syntaxhighlight> |
||
=={{header|Arc}}== |
=={{header|Arc}}== |
||
<syntaxhighlight lang="arc"> |
|||
<lang Arc> |
|||
(= divisor (fn (num) |
(= divisor (fn (num) |
||
(= dlist '()) |
(= dlist '()) |
||
Line 748: | Line 748: | ||
(map [rev _] (map [divisor _] '(45 53 60 64))) |
(map [rev _] (map [divisor _] '(45 53 60 64))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<syntaxhighlight lang="arc"> |
|||
<lang Arc> |
|||
'( |
'( |
||
(1 3 5 9 15 45) |
(1 3 5 9 15 45) |
||
Line 758: | Line 758: | ||
(1 2 4 8 16 32 64) |
(1 2 4 8 16 32 64) |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program factorst.s */ |
/* program factorst.s */ |
||
Line 949: | Line 949: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">factors: $[num][ |
||
select 1..num [x][ |
select 1..num [x][ |
||
(num%x)=0 |
(num%x)=0 |
||
Line 958: | Line 958: | ||
] |
] |
||
print factors 36</ |
print factors 36</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 965: | Line 965: | ||
=={{header|Asymptote}}== |
=={{header|Asymptote}}== |
||
< |
<syntaxhighlight lang="asymptote">int[] n = {11, 21, 32, 45, 67, 519}; |
||
for(var j : n) { |
for(var j : n) { |
||
Line 976: | Line 976: | ||
} |
} |
||
write(" ", j); |
write(" ", j); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>11 => 1 11 |
<pre>11 => 1 11 |
||
Line 986: | Line 986: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">msgbox, % factors(45) "`n" factors(53) "`n" factors(64) |
||
Factors(n) |
Factors(n) |
||
Line 994: | Line 994: | ||
Sort, v, N U D, |
Sort, v, N U D, |
||
Return, v |
Return, v |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,003: | Line 1,003: | ||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
< |
<syntaxhighlight lang="autoit">;AutoIt Version: 3.2.10.0 |
||
$num = 45 |
$num = 45 |
||
MsgBox (0,"Factors", "Factors of " & $num & " are: " & factors($num)) |
MsgBox (0,"Factors", "Factors of " & $num & " are: " & factors($num)) |
||
Line 1,015: | Line 1,015: | ||
Next |
Next |
||
Return $ls_factors&$intg |
Return $ls_factors&$intg |
||
EndFunc</ |
EndFunc</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,023: | Line 1,023: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f FACTORS_OF_AN_INTEGER.AWK |
# syntax: GAWK -f FACTORS_OF_AN_INTEGER.AWK |
||
BEGIN { |
BEGIN { |
||
Line 1,042: | Line 1,042: | ||
printf("\n") |
printf("\n") |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,063: | Line 1,063: | ||
Note that this will error out if you pass 32767 (or higher). |
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 |
REDIM SHARED factors(0) AS INTEGER |
||
Line 1,103: | Line 1,103: | ||
END IF |
END IF |
||
NEXT |
NEXT |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,123: | Line 1,123: | ||
==={{header|ASIC}}=== |
==={{header|ASIC}}=== |
||
{{trans|GW-BASIC}} |
{{trans|GW-BASIC}} |
||
< |
<syntaxhighlight lang="basic"> |
||
REM Factors of an integer |
REM Factors of an integer |
||
PRINT "Enter an integer"; |
PRINT "Enter an integer"; |
||
Line 1,138: | Line 1,138: | ||
NEXT I |
NEXT I |
||
PRINT NA |
PRINT NA |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,148: | Line 1,148: | ||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
<syntaxhighlight lang="basic256"> |
|||
<lang BASIC256> |
|||
subroutine printFactors(n) |
subroutine printFactors(n) |
||
print n; " => "; |
print n; " => "; |
||
Line 1,164: | Line 1,164: | ||
call printFactors(96) |
call printFactors(96) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,172: | Line 1,172: | ||
==={{header|GW-BASIC}}=== |
==={{header|GW-BASIC}}=== |
||
< |
<syntaxhighlight lang="gwbasic"> |
||
10 INPUT "Enter an integer: ", N |
10 INPUT "Enter an integer: ", N |
||
20 IF N = 0 THEN GOTO 10 |
20 IF N = 0 THEN GOTO 10 |
||
Line 1,179: | Line 1,179: | ||
50 IF NA MOD I = 0 THEN PRINT I; |
50 IF NA MOD I = 0 THEN PRINT I; |
||
60 NEXT I |
60 NEXT I |
||
70 PRINT NA</ |
70 PRINT NA</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,193: | Line 1,193: | ||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "Factors.bas" |
||
110 INPUT PROMPT "Number: ":N |
110 INPUT PROMPT "Number: ":N |
||
120 FOR I=1 TO INT(N/2) |
120 FOR I=1 TO INT(N/2) |
||
130 IF MOD(N,I)=0 THEN PRINT I; |
130 IF MOD(N,I)=0 THEN PRINT I; |
||
140 NEXT |
140 NEXT |
||
150 PRINT N</ |
150 PRINT N</syntaxhighlight> |
||
==={{header|Minimal BASIC}}=== |
==={{header|Minimal BASIC}}=== |
||
Line 1,204: | Line 1,204: | ||
{{works with|Commodore BASIC}} |
{{works with|Commodore BASIC}} |
||
{{works with|Nascom ROM BASIC|4.7}} |
{{works with|Nascom ROM BASIC|4.7}} |
||
< |
<syntaxhighlight lang="gwbasic"> |
||
10 REM Factors of an integer |
10 REM Factors of an integer |
||
20 PRINT "Enter an integer"; |
20 PRINT "Enter an integer"; |
||
Line 1,216: | Line 1,216: | ||
100 PRINT N1 |
100 PRINT N1 |
||
110 END |
110 END |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Nascom BASIC}}=== |
==={{header|Nascom BASIC}}=== |
||
{{trans|GW-BASIC}} |
{{trans|GW-BASIC}} |
||
{{works with|Nascom ROM BASIC|4.7}} |
{{works with|Nascom ROM BASIC|4.7}} |
||
< |
<syntaxhighlight lang="basic"> |
||
10 REM Factors of an integer |
10 REM Factors of an integer |
||
20 INPUT "Enter an integer"; N |
20 INPUT "Enter an integer"; N |
||
Line 1,231: | Line 1,231: | ||
80 PRINT NA |
80 PRINT NA |
||
90 END |
90 END |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,241: | Line 1,241: | ||
==={{header|Sinclair ZX81 BASIC}}=== |
==={{header|Sinclair ZX81 BASIC}}=== |
||
{{works with|Applesoft BASIC}} |
{{works with|Applesoft BASIC}} |
||
< |
<syntaxhighlight lang="basic">10 INPUT N |
||
20 FOR I=1 TO N |
20 FOR I=1 TO N |
||
30 IF N/I=INT (N/I) THEN PRINT I;" "; |
30 IF N/I=INT (N/I) THEN PRINT I;" "; |
||
40 NEXT I</ |
40 NEXT I</syntaxhighlight> |
||
{{in}} |
{{in}} |
||
<pre>315</pre> |
<pre>315</pre> |
||
Line 1,251: | Line 1,251: | ||
==={{header|Tiny BASIC}}=== |
==={{header|Tiny BASIC}}=== |
||
< |
<syntaxhighlight lang="tiny basic">100 PRINT "Give me a number:" |
||
110 INPUT I |
110 INPUT I |
||
120 LET C=1 |
120 LET C=1 |
||
Line 1,258: | Line 1,258: | ||
150 LET C=C+1 |
150 LET C=C+1 |
||
160 IF C<=I THEN GOTO 140 |
160 IF C<=I THEN GOTO 140 |
||
170 END</ |
170 END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Give me a number: |
<pre>Give me a number: |
||
Line 1,280: | Line 1,280: | ||
==={{header|True BASIC}}=== |
==={{header|True BASIC}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="qbasic"> |
||
sub printfactors(n) |
sub printfactors(n) |
||
if n < 1 then exit sub |
if n < 1 then exit sub |
||
Line 1,298: | Line 1,298: | ||
print |
print |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,306: | Line 1,306: | ||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Command line version: |
Command line version: |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
set res=Factors of %1: |
set res=Factors of %1: |
||
for /L %%i in (1,1,%1) do call :fac %1 %%i |
for /L %%i in (1,1,%1) do call :fac %1 %%i |
||
Line 1,314: | Line 1,314: | ||
:fac |
:fac |
||
set /a test = %1 %% %2 |
set /a test = %1 %% %2 |
||
if %test% equ 0 set res=%res% %2</ |
if %test% equ 0 set res=%res% %2</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,333: | Line 1,333: | ||
Interactive version: |
Interactive version: |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
set /p limit=Gimme a number: |
set /p limit=Gimme a number: |
||
set res=Factors of %limit%: |
set res=Factors of %limit%: |
||
Line 1,342: | Line 1,342: | ||
:fac |
:fac |
||
set /a test = %1 %% %2 |
set /a test = %1 %% %2 |
||
if %test% equ 0 set res=%res% %2</ |
if %test% equ 0 set res=%res% %2</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,355: | Line 1,355: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB" |
||
sort% = FN_sortinit(0, 0) |
sort% = FN_sortinit(0, 0) |
||
Line 1,379: | Line 1,379: | ||
L$ += STR$(L%(I%)) + ", " |
L$ += STR$(L%(I%)) + ", " |
||
NEXT |
NEXT |
||
= LEFT$(LEFT$(L$))</ |
= LEFT$(LEFT$(L$))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,386: | Line 1,386: | ||
=={{header|bc}}== |
=={{header|bc}}== |
||
< |
<syntaxhighlight lang="bc">/* Calculate the factors of n and return their count. |
||
* This function mutates the global array f[] which will |
* This function mutates the global array f[] which will |
||
* contain all factors of n in ascending order after the call! |
* contain all factors of n in ascending order after the call! |
||
Line 1,429: | Line 1,429: | ||
scale = o |
scale = o |
||
return(l) |
return(l) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
< |
<syntaxhighlight lang="befunge">10:p&v: >:0:g%#v_0:g\:0:g/\v |
||
>:0:g:*`| > >0:g1+0:p |
>:0:g:*`| > >0:g1+0:p |
||
>:0:g:*-#v_0:g\>$>:!#@_.v |
>:0:g:*-#v_0:g\>$>:!#@_.v |
||
> ^ ^ ," "<</ |
> ^ ^ ," "<</syntaxhighlight> |
||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
Line 1,441: | Line 1,441: | ||
A bqncrate idiom. |
A bqncrate idiom. |
||
< |
<syntaxhighlight lang="bqn">Factors ← (1+↕)⊸(⊣/˜0=|) |
||
•Show Factors 12345 |
•Show Factors 12345 |
||
•Show Factors 729</ |
•Show Factors 729</syntaxhighlight> |
||
<lang>⟨ 1 3 5 15 823 2469 4115 12345 ⟩ |
<syntaxhighlight lang="text">⟨ 1 3 5 15 823 2469 4115 12345 ⟩ |
||
⟨ 1 3 9 27 81 243 729 ⟩</ |
⟨ 1 3 9 27 81 243 729 ⟩</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="bqn">⟨FactorExponents⟩ ← •Import "primes.bqn" # With appropriate path |
||
Factors ← { ∧⥊ 1 ×⌜´ ⋆⟜(↕1+⊢)¨˝ FactorExponents 𝕩 }</ |
Factors ← { ∧⥊ 1 ×⌜´ ⋆⟜(↕1+⊢)¨˝ FactorExponents 𝕩 }</syntaxhighlight> |
||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque">blsq ) 32767 fc |
||
{1 7 31 151 217 1057 4681 32767}</ |
{1 7 31 151 217 1057 4681 32767}</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 1,524: | Line 1,524: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
===Prime factoring=== |
===Prime factoring=== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 1,613: | Line 1,613: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,623: | Line 1,623: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
===C# 1.0=== |
===C# 1.0=== |
||
< |
<syntaxhighlight lang="csharp">static void Main (string[] args) { |
||
do { |
do { |
||
Console.WriteLine ("Number:"); |
Console.WriteLine ("Number:"); |
||
Line 1,643: | Line 1,643: | ||
Console.WriteLine ("Done."); |
Console.WriteLine ("Done."); |
||
} while (true); |
} while (true); |
||
}</ |
}</syntaxhighlight> |
||
===C# 3.0=== |
===C# 3.0=== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
using System.Linq; |
using System.Linq; |
||
Line 1,660: | Line 1,660: | ||
Console.WriteLine (String.Join (", ", 45. Factors ())); |
Console.WriteLine (String.Join (", ", 45. Factors ())); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,671: | Line 1,671: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <iomanip> |
#include <iomanip> |
||
#include <vector> |
#include <vector> |
||
Line 1,704: | Line 1,704: | ||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,713: | Line 1,713: | ||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void run() { |
||
{Integer*} getFactors(Integer n) => |
{Integer*} getFactors(Integer n) => |
||
(1..n).filter((Integer element) => element.divides(n)); |
(1..n).filter((Integer element) => element.divides(n)); |
||
Line 1,720: | Line 1,720: | ||
print("the factors of ``i`` are ``getFactors(i)``"); |
print("the factors of ``i`` are ``getFactors(i)``"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
Inspired by the Clojure solution: |
Inspired by the Clojure solution: |
||
< |
<syntaxhighlight lang="chapel">iter factors(n) { |
||
for i in 1..floor(sqrt(n)):int { |
for i in 1..floor(sqrt(n)):int { |
||
if n % i == 0 then { |
if n % i == 0 then { |
||
Line 1,731: | Line 1,731: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">(defn factors [n] |
||
(filter #(zero? (rem n %)) (range 1 (inc n)))) |
(filter #(zero? (rem n %)) (range 1 (inc n)))) |
||
(print (factors 45))</ |
(print (factors 45))</syntaxhighlight> |
||
(1 3 5 9 15 45) |
(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. |
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. |
||
< |
<syntaxhighlight lang="lisp">(defn factors [n] |
||
(into (sorted-set) |
(into (sorted-set) |
||
(mapcat (fn [x] [x (/ n x)]) |
(mapcat (fn [x] [x (/ n x)]) |
||
(filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))) )))</ |
(filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))) )))</syntaxhighlight> |
||
Same idea, using for comprehensions. |
Same idea, using for comprehensions. |
||
< |
<syntaxhighlight lang="lisp">(defn factors [n] |
||
(into (sorted-set) |
(into (sorted-set) |
||
(reduce concat |
(reduce concat |
||
(for [x (range 1 (inc (Math/sqrt n))) :when (zero? (rem n x))] |
(for [x (range 1 (inc (Math/sqrt n))) :when (zero? (rem n x))] |
||
[x (/ n x)]))))</ |
[x (/ n x)]))))</syntaxhighlight> |
||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
{{trans|Sather}} |
{{trans|Sather}} |
||
< |
<syntaxhighlight lang="clu">isqrt = proc (s: int) returns (int) |
||
x0: int := s/2 |
x0: int := s/2 |
||
if x0=0 then return(s) end |
if x0=0 then return(s) end |
||
Line 1,786: | Line 1,786: | ||
stream$putl(po, "") |
stream$putl(po, "") |
||
end |
end |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Factors of 3135: 1 3 1045 5 627 11 285 15 209 19 165 33 95 55 57 3135 |
<pre>Factors of 3135: 1 3 1045 5 627 11 285 15 209 19 165 33 95 55 57 3135 |
||
Line 1,796: | Line 1,796: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> |
||
IDENTIFICATION DIVISION. |
IDENTIFICATION DIVISION. |
||
PROGRAM-ID. FACTORS. |
PROGRAM-ID. FACTORS. |
||
Line 1,837: | Line 1,837: | ||
END PROGRAM FACTORS. |
END PROGRAM FACTORS. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"># Reference implementation for finding factors is slow, but hopefully |
||
# robust--we'll use it to verify the more complicated (but hopefully faster) |
# robust--we'll use it to verify the more complicated (but hopefully faster) |
||
# algorithm. |
# algorithm. |
||
Line 1,898: | Line 1,898: | ||
console.log n, factors |
console.log n, factors |
||
if n < 1000000 |
if n < 1000000 |
||
verify_factors factors, n</ |
verify_factors factors, n</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,925: | Line 1,925: | ||
=={{header|Common Lisp}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="lisp">(defun factors (n &aux (lows '()) (highs '())) |
||
(do ((limit (1+ (isqrt n))) (factor 1 (1+ factor))) |
(do ((limit (1+ (isqrt n))) (factor 1 (1+ factor))) |
||
((= factor limit) |
((= factor limit) |
||
Line 1,934: | Line 1,934: | ||
(when (zerop remainder) |
(when (zerop remainder) |
||
(push factor lows) |
(push factor lows) |
||
(push quotient highs)))))</ |
(push quotient highs)))))</syntaxhighlight> |
||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
Brute force and slow, by checking every value up to n. |
Brute force and slow, by checking every value up to n. |
||
< |
<syntaxhighlight lang="ruby">struct Int |
||
def factors() (1..self).select { |n| (self % n).zero? } end |
def factors() (1..self).select { |n| (self % n).zero? } end |
||
end</ |
end</syntaxhighlight> |
||
Faster, by only checking values up to <math>\sqrt{n}</math>. |
Faster, by only checking values up to <math>\sqrt{n}</math>. |
||
< |
<syntaxhighlight lang="ruby">struct Int |
||
def factors |
def factors |
||
f = [] of Int32 |
f = [] of Int32 |
||
Line 1,952: | Line 1,952: | ||
f.sort |
f.sort |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
'''Tests:''' |
'''Tests:''' |
||
< |
<syntaxhighlight lang="ruby"> |
||
[45, 53, 64].each {|n| puts "#{n} : #{n.factors}"}</ |
[45, 53, 64].each {|n| puts "#{n} : #{n.factors}"}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,965: | Line 1,965: | ||
=={{header|D}}== |
=={{header|D}}== |
||
===Procedural Style=== |
===Procedural Style=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.math, std.algorithm; |
||
T[] factors(T)(in T n) pure nothrow { |
T[] factors(T)(in T n) pure nothrow { |
||
Line 1,987: | Line 1,987: | ||
void main() { |
void main() { |
||
writefln("%(%s\n%)", [45, 53, 64, 1111111].map!factors); |
writefln("%(%s\n%)", [45, 53, 64, 1111111].map!factors); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1, 3, 5, 9, 15, 45] |
<pre>[1, 3, 5, 9, 15, 45] |
||
Line 1,995: | Line 1,995: | ||
===Functional Style=== |
===Functional Style=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range; |
||
auto factors(I)(I n) { |
auto factors(I)(I n) { |
||
Line 2,003: | Line 2,003: | ||
void main() { |
void main() { |
||
36.factors.writeln; |
36.factors.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1, 2, 3, 4, 6, 9, 12, 18, 36]</pre> |
<pre>[1, 2, 3, 4, 6, 9, 12, 18, 36]</pre> |
||
Line 2,032: | Line 2,032: | ||
=={{header|Dc}}== |
=={{header|Dc}}== |
||
=== Simple O(n) version === |
=== Simple O(n) version === |
||
<syntaxhighlight lang="dc"> |
|||
<lang dc> |
|||
[Enter positive number: ]P ? sn |
[Enter positive number: ]P ? sn |
||
[Factors of ]P lnn [ are: ]P |
[Factors of ]P lnn [ are: ]P |
||
[q]sq 1si [[ ]P lin]sp [ li ln <q ln li % 0=p li1+si lxx ]dsxx AP |
[q]sq 1si [[ ]P lin]sp [ li ln <q ln li % 0=p li1+si lxx ]dsxx AP |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Factors of 998877 are: 1 3 11 33 30269 90807 332959 998877 |
Factors of 998877 are: 1 3 11 33 30269 90807 332959 998877 |
||
0m1.120s |
0m1.120s |
||
=== Faster O(sqrt(n)) version === |
=== Faster O(sqrt(n)) version === |
||
<syntaxhighlight lang="dc"> |
|||
<lang dc> |
|||
[Enter positive number: ]P ? sn |
[Enter positive number: ]P ? sn |
||
[Factors of ]P lnn [ are: ]P |
[Factors of ]P lnn [ are: ]P |
||
Line 2,047: | Line 2,047: | ||
[li lv <q ln li % 0=P li1+si lxx]dsxx |
[li lv <q ln li % 0=P li1+si lxx]dsxx |
||
[lj 1>q lj1-sj Lbsi lpx lxx]dsxx AP |
[lj 1>q lj1-sj Lbsi lpx lxx]dsxx AP |
||
</syntaxhighlight> |
|||
</lang> |
|||
0m0.004s |
0m0.004s |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Line 2,053: | Line 2,053: | ||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">func Iterator.Where(pred) { |
||
for x in this when pred(x) { |
for x in this when pred(x) { |
||
yield x |
yield x |
||
Line 2,065: | Line 2,065: | ||
for x in 45.Factors() { |
for x in 45.Factors() { |
||
print(x) |
print(x) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,078: | Line 2,078: | ||
=={{header|E}}== |
=={{header|E}}== |
||
{{improve|E|Use a cleverer algorithm such as in the Common Lisp example.}} |
{{improve|E|Use a cleverer algorithm such as in the Common Lisp example.}} |
||
< |
<syntaxhighlight lang="e">def factors(x :(int > 0)) { |
||
var xfactors := [] |
var xfactors := [] |
||
for f ? (x % f <=> 0) in 1..x { |
for f ? (x % f <=> 0) in 1..x { |
||
Line 2,084: | Line 2,084: | ||
} |
} |
||
return xfactors |
return xfactors |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
<lang>n = 720 |
<syntaxhighlight lang="text">n = 720 |
||
for i = 1 to n |
for i = 1 to n |
||
if n mod i = 0 |
if n mod i = 0 |
||
Line 2,093: | Line 2,093: | ||
. |
. |
||
. |
. |
||
print factors[]</ |
print factors[]</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
'''prime-factors''' gives the list of n's prime-factors. We mix them to get all the factors. |
'''prime-factors''' gives the list of n's prime-factors. We mix them to get all the factors. |
||
< |
<syntaxhighlight lang="scheme"> |
||
;; ppows |
;; ppows |
||
;; input : a list g of grouped prime factors ( 3 3 3 ..) |
;; input : a list g of grouped prime factors ( 3 3 3 ..) |
||
Line 2,116: | Line 2,116: | ||
(for/fold (divs'(1)) ((g (map ppows (group (prime-factors n))))) |
(for/fold (divs'(1)) ((g (map ppows (group (prime-factors n))))) |
||
(for*/list ((a divs) (b g)) (* a b)))))) |
(for*/list ((a divs) (b g)) (* a b)))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lib 'bigint) |
(lib 'bigint) |
||
(factors 666) |
(factors 666) |
||
Line 2,129: | Line 2,129: | ||
(time ( length (factors huge))) |
(time ( length (factors huge))) |
||
→ (394ms 7776) |
→ (394ms 7776) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
Line 2,136: | Line 2,136: | ||
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). |
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). |
||
< |
<syntaxhighlight lang="edsac"> |
||
[Factors of an integer, from Rosetta Code website.] |
[Factors of an integer, from Rosetta Code website.] |
||
[EDSAC program, Initial Orders 2.] |
[EDSAC program, Initial Orders 2.] |
||
Line 2,290: | Line 2,290: | ||
E 4 Z [define entry point] |
E 4 Z [define entry point] |
||
P F [acc = 0 on entry] |
P F [acc = 0 on entry] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,317: | Line 2,317: | ||
===Using higher-order function=== |
===Using higher-order function=== |
||
< |
<syntaxhighlight lang="ela">open list |
||
factors m = filter (\x -> m % x == 0) [1..m]</ |
factors m = filter (\x -> m % x == 0) [1..m]</syntaxhighlight> |
||
===Using comprehension=== |
===Using comprehension=== |
||
< |
<syntaxhighlight lang="ela">factors m = [x \\ x <- [1..m] | m % x == 0]</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule RC do |
||
def factor(1), do: [1] |
def factor(1), do: [1] |
||
def factor(n) do |
def factor(n) do |
||
Line 2,351: | Line 2,351: | ||
IO.puts "#{name}\t prime count : #{value},\t#{time/1000000} sec" |
IO.puts "#{name}\t prime count : #{value},\t#{time/1000000} sec" |
||
end) |
end) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,367: | Line 2,367: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
===with Built in fuctions=== |
===with Built in fuctions=== |
||
< |
<syntaxhighlight lang="erlang">factors(N) -> |
||
[I || I <- lists:seq(1,trunc(N/2)), N rem I == 0]++[N].</ |
[I || I <- lists:seq(1,trunc(N/2)), N rem I == 0]++[N].</syntaxhighlight> |
||
===Recursive=== |
===Recursive=== |
||
Another, less concise, but faster version |
Another, less concise, but faster version |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(divs). |
-module(divs). |
||
Line 2,391: | Line 2,391: | ||
divisors(K,N,_Q) -> |
divisors(K,N,_Q) -> |
||
[K, N div K] ++ divisors(K+1,N,math:sqrt(N)). |
[K, N div K] ++ divisors(K+1,N,math:sqrt(N)). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,407: | Line 2,407: | ||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM FACTORS |
PROGRAM FACTORS |
||
Line 2,451: | Line 2,451: | ||
PRINT("The factors of 12345 are ";L$) |
PRINT("The factors of 12345 are ";L$) |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,467: | Line 2,467: | ||
{{Works with|Office 365 Betas 2021}} |
{{Works with|Office 365 Betas 2021}} |
||
< |
<syntaxhighlight lang="lisp">=LAMBDA(n, |
||
IF(1 < n, |
IF(1 < n, |
||
LET( |
LET( |
||
Line 2,490: | Line 2,490: | ||
IF(1 = n, {1}, NA()) |
IF(1 = n, {1}, NA()) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
and assuming that in the same worksheet, each of the following names is bound to the reusable generic lambda expression which follows it: |
and assuming that in the same worksheet, each of the following names is bound to the reusable generic lambda expression which follows it: |
||
< |
<syntaxhighlight lang="lisp">APPEND |
||
=LAMBDA(xs, |
=LAMBDA(xs, |
||
LAMBDA(ys, |
LAMBDA(ys, |
||
Line 2,552: | Line 2,552: | ||
) |
) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
The '''FACTORS''' function, applied to an integer, defines a column of integer values. |
The '''FACTORS''' function, applied to an integer, defines a column of integer values. |
||
Line 2,742: | Line 2,742: | ||
Also, this is lazily evaluated. |
Also, this is lazily evaluated. |
||
< |
<syntaxhighlight lang="fsharp">let factors number = seq { |
||
for divisor in 1 .. (float >> sqrt >> int) number do |
for divisor in 1 .. (float >> sqrt >> int) number do |
||
if number % divisor = 0 then |
if number % divisor = 0 then |
||
yield divisor |
yield divisor |
||
if number <> 1 then yield number / divisor //special case condition: when number=1 then divisor=(number/divisor), so don't repeat it |
if number <> 1 then yield number / divisor //special case condition: when number=1 then divisor=(number/divisor), so don't repeat it |
||
}</ |
}</syntaxhighlight> |
||
===Prime factoring=== |
===Prime factoring=== |
||
< |
<syntaxhighlight 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 "");;</ |
[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 "");;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,771: | Line 2,771: | ||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
< |
<syntaxhighlight lang="false">[1[\$@$@-][\$@$@$@$@\/*=[$." "]?1+]#.%]f: |
||
45f;! 53f;! 64f;!</ |
45f;! 53f;! 64f;!</syntaxhighlight> |
||
=={{header|Fish}}== |
=={{header|Fish}}== |
||
<syntaxhighlight lang="fish">0v |
|||
<lang Fish>0v |
|||
>i:0(?v'0'%+a* |
>i:0(?v'0'%+a* |
||
>~a,:1:>r{% ?vr:nr','ov |
>~a,:1:>r{% ?vr:nr','ov |
||
^:&:;?(&:+1r:< < |
^:&:;?(&:+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]. |
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> |
For Input Number : <pre> 120</pre> |
||
Line 2,787: | Line 2,787: | ||
=={{header|Forth}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="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 ; |
: .factors factors begin dup dup . 1 <> while drop repeat drop cr ; |
||
Line 2,793: | Line 2,793: | ||
53 .factors |
53 .factors |
||
64 .factors |
64 .factors |
||
100 .factors</ |
100 .factors</syntaxhighlight> |
||
=== Alternative version with vectored execution === |
=== 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. |
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 |
: sq s" dup *" evaluate ; immediate |
||
Line 2,824: | Line 2,824: | ||
0 :noname swap . ; <with-factors> (.factors) |
0 :noname swap . ; <with-factors> (.factors) |
||
: .factors (.factors) drop ; |
: .factors (.factors) drop ; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 2,837: | Line 2,837: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">program Factors |
||
implicit none |
implicit none |
||
integer :: i, number |
integer :: i, number |
||
Line 2,856: | Line 2,856: | ||
end if |
end if |
||
end program</ |
end program</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Sub printFactors(n As Integer) |
Sub printFactors(n As Integer) |
||
Line 2,878: | Line 2,878: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,899: | Line 2,899: | ||
The following produces all factors of n, including 1 and n: |
The following produces all factors of n, including 1 and n: |
||
<lang |
<syntaxhighlight lang="frink">allFactors[n]</syntaxhighlight> |
||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
Function to compute set of factors: |
Function to compute set of factors: |
||
< |
<syntaxhighlight lang="funl">def factors( n ) = {d | d <- 1..n if d|n}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="funl">for x <- [103, 316, 519, 639, 760] |
||
println( 'The set of factors of ' + x + ' is ' + factors(x) )</ |
println( 'The set of factors of ' + x + ' is ' + factors(x) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,920: | Line 2,920: | ||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
< |
<syntaxhighlight lang="futurebasic">window 1, @"Factors of an Integer", (0,0,1000,270) |
||
clear local mode |
clear local mode |
||
Line 2,969: | Line 2,969: | ||
print @"Factors of 32434243 are:"; fn IntegerFactors( 32434243 ) |
print @"Factors of 32434243 are:"; fn IntegerFactors( 32434243 ) |
||
HandleEvents</ |
HandleEvents</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,986: | Line 2,986: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># Built-in function |
||
DivisorsInt(Factorial(5)); |
DivisorsInt(Factorial(5)); |
||
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ] |
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ] |
||
Line 3,005: | Line 3,005: | ||
div2(Factorial(5)); |
div2(Factorial(5)); |
||
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]</ |
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]</syntaxhighlight> |
||
=={{header|Go}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 3,060: | Line 3,060: | ||
fmt.Println(fs) |
fmt.Println(fs) |
||
fmt.Println("Number of factors =", len(fs)) |
fmt.Println("Number of factors =", len(fs)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,092: | Line 3,092: | ||
=={{header|Gosu}}== |
=={{header|Gosu}}== |
||
< |
<syntaxhighlight lang="gosu">var numbers = {11, 21, 32, 45, 67, 96} |
||
numbers.each(\ number -> printFactors(number)) |
numbers.each(\ number -> printFactors(number)) |
||
Line 3,100: | Line 3,100: | ||
(1 .. n/2).each(\ i -> {result += n % i == 0 ? "${i} " : ""}) |
(1 .. n/2).each(\ i -> {result += n % i == 0 ? "${i} " : ""}) |
||
print("${result}${n}") |
print("${result}${n}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,114: | Line 3,114: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
A straight brute force approach up to the square root of ''N'': |
A straight brute force approach up to the square root of ''N'': |
||
< |
<syntaxhighlight lang="groovy">def factorize = { long target -> |
||
if (target == 1) return [1L] |
if (target == 1) return [1L] |
||
Line 3,126: | Line 3,126: | ||
[1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target] |
[1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target] |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="groovy">((1..30) + [333333]).each { println ([number:it, factors:factorize(it)]) }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[number:1, factors:[1]] |
<pre>[number:1, factors:[1]] |
||
Line 3,165: | Line 3,165: | ||
=={{header|Haskell}}== |
=={{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 |
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 |
||
< |
<syntaxhighlight lang="haskell">import HFM.Primes (primePowerFactors) |
||
import Control.Monad (mapM) |
import Control.Monad (mapM) |
||
import Data.List (product) |
import Data.List (product) |
||
Line 3,172: | Line 3,172: | ||
factors = map product . |
factors = map product . |
||
mapM (\(p,m)-> [p^i | i<-[0..m]]) . primePowerFactors</ |
mapM (\(p,m)-> [p^i | i<-[0..m]]) . primePowerFactors</syntaxhighlight> |
||
Returns list of factors out of order, e.g.: |
Returns list of factors out of order, e.g.: |
||
<Lang haskell>~> factors 42 |
<Lang haskell>~> factors 42 |
||
[1,7,3,21,2,14,6,42]</ |
[1,7,3,21,2,14,6,42]</syntaxhighlight> |
||
Or, [[Prime_decomposition#Haskell|prime decomposition task]] can be used (although, a trial division-only version will become very slow for large primes), |
Or, [[Prime_decomposition#Haskell|prime decomposition task]] can be used (although, a trial division-only version will become very slow for large primes), |
||
< |
<syntaxhighlight lang="haskell">import Data.List (group) |
||
primePowerFactors = map (\x-> (head x, length x)) . group . factorize</ |
primePowerFactors = map (\x-> (head x, length x)) . group . factorize</syntaxhighlight> |
||
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". |
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,188: | Line 3,188: | ||
Or, deriving cofactors from factors up to the square root: |
Or, deriving cofactors from factors up to the square root: |
||
< |
<syntaxhighlight lang="haskell">integerFactors :: Int -> [Int] |
||
integerFactors n |
integerFactors n |
||
| 1 > n = [] |
| 1 > n = [] |
||
Line 3,202: | Line 3,202: | ||
main :: IO () |
main :: IO () |
||
main = print $ integerFactors 600</ |
main = print $ integerFactors 600</syntaxhighlight> |
||
{{Out}} |
{{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> |
<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,208: | Line 3,208: | ||
=== List comprehension === |
=== List comprehension === |
||
Naive, functional, no import, in increasing order: |
Naive, functional, no import, in increasing order: |
||
< |
<syntaxhighlight lang="haskell">factorsNaive n = |
||
[ i |
[ i |
||
| i <- [1 .. n] |
| i <- [1 .. n] |
||
, mod n i == 0 ]</ |
, mod n i == 0 ]</syntaxhighlight> |
||
< |
<syntaxhighlight lang="haskell">~> factorsNaive 25 |
||
[1,5,25]</ |
[1,5,25]</syntaxhighlight> |
||
Factor, ''cofactor''. Get the list of factor–cofactor pairs sorted, for a quadratic speedup: |
Factor, ''cofactor''. Get the list of factor–cofactor pairs sorted, for a quadratic speedup: |
||
< |
<syntaxhighlight lang="haskell">import Data.List (sort) |
||
factorsCo n = |
factorsCo n = |
||
Line 3,226: | Line 3,226: | ||
i : |
i : |
||
[ d |
[ d |
||
| d > i ] ]</ |
| d > i ] ]</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="haskell">factorsO n = |
||
ds ++ |
ds ++ |
||
[ r |
[ r |
||
Line 3,243: | Line 3,243: | ||
[ i |
[ i |
||
| i <- [1 .. r - 1] |
| i <- [1 .. r - 1] |
||
, mod n i == 0 ]</ |
, mod n i == 0 ]</syntaxhighlight> |
||
Testing: |
Testing: |
||
< |
<syntaxhighlight lang="haskell">*Main> :set +s |
||
~> factorsO 120 |
~> factorsO 120 |
||
[1,2,3,4,5,6,8,10,12,15,20,24,30,40,60,120] |
[1,2,3,4,5,6,8,10,12,15,20,24,30,40,60,120] |
||
Line 3,253: | Line 3,253: | ||
[1,7,41,287,541,3787,22181,77551,155267,542857,3179591,22257137,41955091,2936856 |
[1,7,41,287,541,3787,22181,77551,155267,542857,3179591,22257137,41955091,2936856 |
||
37,1720158731,12041111117] |
37,1720158731,12041111117] |
||
(0.09 secs, 50758224 bytes)</ |
(0.09 secs, 50758224 bytes)</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest"> DLG(NameEdit=N, TItle='Enter an integer') |
||
DO i = 1, N^0.5 |
DO i = 1, N^0.5 |
||
Line 3,262: | Line 3,262: | ||
ENDDO |
ENDDO |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main(arglist) |
||
numbers := arglist ||| [ 32767, 45, 53, 64, 100] # combine command line provided and default set of values |
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" |
every writes(lf,"factors of ",i := !numbers,"=") & writes(divisors(i)," ") do lf := "\n" |
||
end |
end |
||
link factors</ |
link factors</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,284: | Line 3,284: | ||
The "brute force" approach is the most concise: |
The "brute force" approach is the most concise: |
||
< |
<syntaxhighlight lang="j">foi=: [: I. 0 = (|~ i.@>:)</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="j"> foi 40 |
||
1 2 4 5 8 10 20 40</ |
1 2 4 5 8 10 20 40</syntaxhighlight> |
||
Basically we test every non-negative integer up through the number itself to see if it divides evenly. |
Basically we test every non-negative integer up through the number itself to see if it divides evenly. |
||
Line 3,296: | Line 3,296: | ||
J has a primitive, q: which returns its argument's prime factors. |
J has a primitive, q: which returns its argument's prime factors. |
||
< |
<syntaxhighlight lang="j">q: 40 |
||
2 2 2 5</ |
2 2 2 5</syntaxhighlight> |
||
Alternatively, q: can produce provide a table of the exponents of the unique relevant prime factors |
Alternatively, q: can produce provide a table of the exponents of the unique relevant prime factors |
||
< |
<syntaxhighlight lang="j"> __ q: 420 |
||
2 3 5 7 |
2 3 5 7 |
||
2 1 1 1</ |
2 1 1 1</syntaxhighlight> |
||
With this, we can form lists of each of the potential relevant powers of each of these prime factors |
With this, we can form lists of each of the potential relevant powers of each of these prime factors |
||
< |
<syntaxhighlight lang="j"> (^ i.@>:)&.>/ __ q: 420 |
||
┌─────┬───┬───┬───┐ |
┌─────┬───┬───┬───┐ |
||
│1 2 4│1 3│1 5│1 7│ |
│1 2 4│1 3│1 5│1 7│ |
||
└─────┴───┴───┴───┘</ |
└─────┴───┴───┴───┘</syntaxhighlight> |
||
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 |
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 |
||
< |
<syntaxhighlight lang="j">factrs=: */&>@{@((^ i.@>:)&.>/)@q:~&__ |
||
factrs 40 |
factrs 40 |
||
1 5 |
1 5 |
||
2 10 |
2 10 |
||
4 20 |
4 20 |
||
8 40</ |
8 40</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="j"> factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ |
||
factors 420 |
factors 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</ |
1 2 3 4 5 6 7 10 12 14 15 20 21 28 30 35 42 60 70 84 105 140 210 420</syntaxhighlight> |
||
A less efficient, but concise variation on this theme: |
A less efficient, but concise variation on this theme: |
||
< |
<syntaxhighlight lang="j"> ~.,*/&> { 1 ,&.> q: 40 |
||
1 5 2 10 4 20 8 40</ |
1 5 2 10 4 20 8 40</syntaxhighlight> |
||
This computes 2^n intermediate values where n is the number of prime factors of the original number. |
This computes 2^n intermediate values where n is the number of prime factors of the original number. |
||
Line 3,333: | Line 3,333: | ||
That said, note that we get a representation issue when dealing with large numbers: |
That said, note that we get a representation issue when dealing with large numbers: |
||
< |
<syntaxhighlight lang="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</ |
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</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="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</ |
1 2 4 5 10 17 20 34 68 85 170 340 1671983 3343966 6687932 8359915 16719830 28423711 33439660 56847422 113694844 142118555 284237110 568474220</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="j">factorsOfNumber=: monad define |
||
Y=. y"_ |
Y=. y"_ |
||
/:~ ~. ( , Y%]) ( #~ 0=]|Y) 1+i.>.%:y |
/:~ ~. ( , Y%]) ( #~ 0=]|Y) 1+i.>.%:y |
||
Line 3,348: | Line 3,348: | ||
factorsOfNumber 40 |
factorsOfNumber 40 |
||
1 2 4 5 8 10 20 40</ |
1 2 4 5 8 10 20 40</syntaxhighlight> |
||
Another approach: |
Another approach: |
||
< |
<syntaxhighlight lang="j">odometer =: #: i.@(*/) |
||
factors=: (*/@:^"1 odometer@:>:)/@q:~&__</ |
factors=: (*/@:^"1 odometer@:>:)/@q:~&__</syntaxhighlight> |
||
See http://www.jsoftware.com/jwiki/Essays/Odometer |
See http://www.jsoftware.com/jwiki/Essays/Odometer |
||
Line 3,359: | Line 3,359: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|5+}} |
{{works with|Java|5+}} |
||
< |
<syntaxhighlight lang="java5">public static TreeSet<Long> factors(long n) |
||
{ |
{ |
||
TreeSet<Long> factors = new TreeSet<Long>(); |
TreeSet<Long> factors = new TreeSet<Long>(); |
||
Line 3,371: | Line 3,371: | ||
} |
} |
||
return factors; |
return factors; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 3,377: | Line 3,377: | ||
===Imperative=== |
===Imperative=== |
||
< |
<syntaxhighlight lang="javascript">function factors(num) |
||
{ |
{ |
||
var |
var |
||
Line 3,396: | Line 3,396: | ||
factors(45); // [1,3,5,9,15,45] |
factors(45); // [1,3,5,9,15,45] |
||
factors(53); // [1,53] |
factors(53); // [1,53] |
||
factors(64); // [1,2,4,8,16,32,64]</ |
factors(64); // [1,2,4,8,16,32,64]</syntaxhighlight> |
||
===Functional=== |
===Functional=== |
||
Line 3,404: | Line 3,404: | ||
Translating the naive list comprehension example from Haskell, using a list monad for the comprehension |
Translating the naive list comprehension example from Haskell, using a list monad for the comprehension |
||
< |
<syntaxhighlight lang="javascript">// Monadic bind (chain) for lists |
||
function chain(xs, f) { |
function chain(xs, f) { |
||
return [].concat.apply([], xs.map(f)); |
return [].concat.apply([], xs.map(f)); |
||
Line 3,422: | Line 3,422: | ||
} |
} |
||
factors_naive(6)</ |
factors_naive(6)</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="javascript">[1, 2, 3, 6]</syntaxhighlight> |
||
Translating the Haskell (lows and highs) example |
Translating the Haskell (lows and highs) example |
||
< |
<syntaxhighlight lang="javascript">console.log( |
||
(function (lstTest) { |
(function (lstTest) { |
||
Line 3,487: | Line 3,487: | ||
})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767]) |
})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767]) |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="javascript">integerFactors(n) |
||
25 --> 1 5 25 |
25 --> 1 5 25 |
||
Line 3,503: | Line 3,503: | ||
32766 --> 1 2 3 6 43 86 127 129 254 258 381 762 5461 10922 16383 32766 |
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 |
32767 --> 1 7 31 151 217 1057 4681 32767 |
||
</syntaxhighlight> |
|||
</lang> |
|||
====ES6==== |
====ES6==== |
||
< |
<syntaxhighlight lang="javascript">(function (lstTest) { |
||
'use strict'; |
'use strict'; |
||
Line 3,580: | Line 3,580: | ||
) + '\n'; |
) + '\n'; |
||
})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767]);</ |
})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767]);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 3,600: | Line 3,600: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
{{Works with|jq|1.4}} |
{{Works with|jq|1.4}} |
||
< |
<syntaxhighlight lang="jq"># This implementation uses "sort" for tidiness |
||
def factors: |
def factors: |
||
. as $num |
. as $num |
||
Line 3,615: | Line 3,615: | ||
(45, 53, 64) | "\(.): \(factors)" ; |
(45, 53, 64) | "\(.): \(factors)" ; |
||
task</ |
task</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
$ jq -n -M -r -c -f factors.jq |
$ jq -n -M -r -c -f factors.jq |
||
Line 3,623: | Line 3,623: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">using Primes |
||
function factors(n) |
function factors(n) |
||
Line 3,638: | Line 3,638: | ||
@time println("The factors of $n are: $(factors(n))") |
@time println("The factors of $n are: $(factors(n))") |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,668: | Line 3,668: | ||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k"> f:{i:{y[&x=y*x div y]}[x;1+!_sqrt x];?i,x div|i} |
||
equivalent to: |
equivalent to: |
||
q)f:{i:{y where x=y*x div y}[x ; 1+ til floor sqrt x]; distinct i,x div reverse i} |
q)f:{i:{y where x=y*x div y}[x ; 1+ til floor sqrt x]; distinct i,x div reverse i} |
||
Line 3,686: | Line 3,686: | ||
/ Number of factors for 3491888400 .. 3491888409 |
/ Number of factors for 3491888400 .. 3491888409 |
||
#:'f' 3491888400+!10 |
#:'f' 3491888400+!10 |
||
1920 16 4 4 12 16 32 16 8 24</ |
1920 16 4 4 12 16 32 16 8 24</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">fun printFactors(n: Int) { |
||
if (n < 1) return |
if (n < 1) return |
||
print("$n => ") |
print("$n => ") |
||
Line 3,701: | Line 3,701: | ||
val numbers = intArrayOf(11, 21, 32, 45, 67, 96) |
val numbers = intArrayOf(11, 21, 32, 45, 67, 96) |
||
for (number in numbers) printFactors(number) |
for (number in numbers) printFactors(number) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,714: | Line 3,714: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
{def factors |
{def factors |
||
{def factors.r |
{def factors.r |
||
Line 3,738: | Line 3,738: | ||
-> 1 2 4 8 16 32 64 |
-> 1 2 4 8 16 32 64 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
Line 3,745: | Line 3,745: | ||
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): |
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): |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun factors (n) |
(defun factors (n) |
||
(list-comp |
(list-comp |
||
((<- i (when (== 0 (rem n i))) (lists:seq 1 (trunc (/ n 2))))) |
((<- i (when (== 0 (rem n i))) (lists:seq 1 (trunc (/ n 2))))) |
||
i)) |
i)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Non-Stack-Consuming=== |
===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): |
This version will not consume the stack (this function only used 18MB of memory on my machine with a ridiculously large number): |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun factors (n) |
(defun factors (n) |
||
"Tail-recursive prime factors function." |
"Tail-recursive prime factors function." |
||
Line 3,768: | Line 3,768: | ||
((n k acc) |
((n k acc) |
||
(factors n (+ k 1) acc))) |
(factors n (+ k 1) acc))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,777: | Line 3,777: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">num = 10677106534462215678539721403561279 |
||
maxnFactors = 1000 |
maxnFactors = 1000 |
||
dim primeFactors(maxnFactors), nPrimeFactors(maxnFactors) |
dim primeFactors(maxnFactors), nPrimeFactors(maxnFactors) |
||
Line 3,849: | Line 3,849: | ||
next i |
next i |
||
end if |
end if |
||
end function</ |
end function</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="lb">Start finding all factors of 10677106534462215678539721403561279: |
||
10677106534462215678539721403561279 = 29269^1 * 32579^1 * 98731^2 * 104729^3 |
10677106534462215678539721403561279 = 29269^1 * 32579^1 * 98731^2 * 104729^3 |
||
1 1 |
1 1 |
||
Line 3,902: | Line 3,902: | ||
47 364792324112959639158827476291 |
47 364792324112959639158827476291 |
||
48 10677106534462215678539721403561279 |
48 10677106534462215678539721403561279 |
||
done</ |
done</syntaxhighlight> |
||
===A Simpler Approach=== |
===A Simpler Approach=== |
||
This is a somewhat simpler approach for finding the factors of smaller numbers (less than one million). |
This is a somewhat simpler approach for finding the factors of smaller numbers (less than one million). |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
print "ROSETTA CODE - Factors of an integer" |
print "ROSETTA CODE - Factors of an integer" |
||
'A simpler approach for smaller numbers |
'A simpler approach for smaller numbers |
||
Line 3,944: | Line 3,944: | ||
next y |
next y |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,971: | Line 3,971: | ||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">on factors(n) |
||
res = [1] |
res = [1] |
||
repeat with i = 2 to n/2 |
repeat with i = 2 to n/2 |
||
Line 3,978: | Line 3,978: | ||
res.add(n) |
res.add(n) |
||
return res |
return res |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lingo">put factors(45) |
||
-- [1, 3, 5, 9, 15, 45] |
-- [1, 3, 5, 9, 15, 45] |
||
put factors(53) |
put factors(53) |
||
-- [1, 53] |
-- [1, 53] |
||
put factors(64) |
put factors(64) |
||
-- [1, 2, 4, 8, 16, 32, 64]</ |
-- [1, 2, 4, 8, 16, 32, 64]</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to factors :n |
||
output filter [equal? 0 modulo :n ?] iseq 1 :n |
output filter [equal? 0 modulo :n ?] iseq 1 :n |
||
end |
end |
||
show factors 28 ; [1 2 4 7 14 28]</ |
show factors 28 ; [1 2 4 7 14 28]</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function Factors( n ) |
||
local f = {} |
local f = {} |
||
Line 4,005: | Line 4,005: | ||
return f |
return f |
||
end</ |
end</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
\\ Factors of an integer |
\\ Factors of an integer |
||
\\ For act as BASIC's FOR (if N<1 no loop start) |
\\ For act as BASIC's FOR (if N<1 no loop start) |
||
Line 4,033: | Line 4,033: | ||
CALL LikeM2000 |
CALL LikeM2000 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
numtheory:-divisors(n); |
numtheory:-divisors(n); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Factorize[n_Integer] := Divisors[n]</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang="matlab"> function fact(n); |
||
f = factor(n); % prime decomposition |
f = factor(n); % prime decomposition |
||
K = dec2bin(0:2^length(f)-1)-'0'; % generate all possible permutations |
K = dec2bin(0:2^length(f)-1)-'0'; % generate all possible permutations |
||
Line 4,056: | Line 4,056: | ||
disp(F); |
disp(F); |
||
end; |
end; |
||
</ |
</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,076: | Line 4,076: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
The builtin <code>divisors</code> function does this. |
The builtin <code>divisors</code> function does this. |
||
< |
<syntaxhighlight lang="maxima">(%i96) divisors(100); |
||
(%o96) {1,2,4,5,10,20,25,50,100}</ |
(%o96) {1,2,4,5,10,20,25,50,100}</syntaxhighlight> |
||
Such a function could be implemented like so: |
Such a function could be implemented like so: |
||
< |
<syntaxhighlight lang="maxima">divisors2(n) := map( lambda([l], lreduce("*", l)), |
||
apply( cartesian_product, |
apply( cartesian_product, |
||
map( lambda([fac], |
map( lambda([fac], |
||
setify(makelist(fac[1]^i, i, 0, fac[2]))), |
setify(makelist(fac[1]^i, i, 0, fac[2]))), |
||
ifactors(n))));</ |
ifactors(n))));</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
<syntaxhighlight lang="maxscript"> |
|||
<lang MAXScript> |
|||
fn factors n = |
fn factors n = |
||
( |
( |
||
return (for i = 1 to n+1 where mod n i == 0 collect i) |
return (for i = 1 to n+1 where mod n i == 0 collect i) |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<syntaxhighlight lang="maxscript"> |
|||
<lang MAXScript> |
|||
factors 3 |
factors 3 |
||
#(1, 3) |
#(1, 3) |
||
Line 4,106: | Line 4,106: | ||
factors 54 |
factors 54 |
||
#(1, 2, 3, 6, 9, 18, 27, 54) |
#(1, 2, 3, 6, 9, 18, 27, 54) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
Line 4,123: | Line 4,123: | ||
===fac.m=== |
===fac.m=== |
||
< |
<syntaxhighlight lang="mercury">:- module fac. |
||
:- interface. |
:- interface. |
||
Line 4,162: | Line 4,162: | ||
factor(N) = Factors :- factor(N, Factors). |
factor(N) = Factors :- factor(N, Factors). |
||
:- end_module fac.</ |
:- end_module fac.</syntaxhighlight> |
||
===Use and output=== |
===Use and output=== |
||
Line 4,174: | Line 4,174: | ||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.6}} |
{{works with|min|0.19.6}} |
||
< |
<syntaxhighlight lang="min">(mod 0 ==) :divisor? |
||
(() 0 shorten) :new |
(() 0 shorten) :new |
||
(new (over swons 'pred dip) pick times nip) :iota |
(new (over swons 'pred dip) pick times nip) :iota |
||
Line 4,189: | Line 4,189: | ||
24 factors puts! |
24 factors puts! |
||
9 factors puts! |
9 factors puts! |
||
11 factors puts!</ |
11 factors puts!</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">factors = function(n) |
||
result = [1] |
result = [1] |
||
for i in range(2, n) |
for i in range(2, n) |
||
Line 4,204: | Line 4,204: | ||
if n <= 0 then break |
if n <= 0 then break |
||
print factors(n) |
print factors(n) |
||
end while</ |
end while</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Number to factor (0 to quit)? 42 |
<pre>Number to factor (0 to quit)? 42 |
||
Line 4,223: | Line 4,223: | ||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<syntaxhighlight lang="mumps">factors(num) New fctr,list,sep,sqrt |
||
If num<1 Quit "Too small a number" |
If num<1 Quit "Too small a number" |
||
If num["." Quit "Not an integer" |
If num["." Quit "Not an integer" |
||
Line 4,233: | Line 4,233: | ||
w $$factors(45) ; [1,3,5,9,15,45] |
w $$factors(45) ; [1,3,5,9,15,45] |
||
w $$factors(53) ; [1,53] |
w $$factors(53) ; [1,53] |
||
w $$factors(64) ; [1,2,4,8,16,32,64]</ |
w $$factors(64) ; [1,2,4,8,16,32,64]</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang="nanoquery">n = int(input()) |
||
for i in range(1, n / 2) |
for i in range(1, n / 2) |
||
Line 4,243: | Line 4,243: | ||
end |
end |
||
end |
end |
||
println n</ |
println n</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
{{trans|REXX}} |
{{trans|REXX}} |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx *********************************************************** |
||
* 21.04.2013 Walter Pachl |
* 21.04.2013 Walter Pachl |
||
* 21.04.2013 add method main to accept argument(s) |
* 21.04.2013 add method main to accept argument(s) |
||
Line 4,281: | Line 4,281: | ||
If j*j=x Then /*for a square number as input */ |
If j*j=x Then /*for a square number as input */ |
||
lo=lo j /* add its square root */ |
lo=lo j /* add its square root */ |
||
return lo hi /* return both lists */</ |
return lo hi /* return both lists */</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,297: | Line 4,297: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import intsets, math, algorithm |
||
proc factors(n: int): seq[int] = |
proc factors(n: int): seq[int] = |
||
Line 4,310: | Line 4,310: | ||
result.sort() |
result.sort() |
||
echo factors(45)</ |
echo factors(45)</syntaxhighlight> |
||
=={{header|Niue}}== |
=={{header|Niue}}== |
||
< |
<syntaxhighlight lang="niue">[ 'n ; [ negative-or-zero [ , ] if |
||
[ n not-factor [ , ] when ] else ] n times n ] 'factors ; |
[ n not-factor [ , ] when ] else ] n times n ] 'factors ; |
||
Line 4,323: | Line 4,323: | ||
53 factors .s .clr ( => 1 53 ) newline |
53 factors .s .clr ( => 1 53 ) newline |
||
64 factors .s .clr ( => 1 2 4 8 16 32 64 ) newline |
64 factors .s .clr ( => 1 2 4 8 16 32 64 ) newline |
||
12 factors .s .clr ( => 1 2 3 4 6 12 ) </ |
12 factors .s .clr ( => 1 2 3 4 6 12 ) </syntaxhighlight> |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Oxford Oberon-2 |
Oxford Oberon-2 |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE Factors; |
MODULE Factors; |
||
IMPORT Out,SYSTEM; |
IMPORT Out,SYSTEM; |
||
Line 4,393: | Line 4,393: | ||
Out.Int(v.len,6);Out.String(" factors");Out.Ln |
Out.Int(v.len,6);Out.String(" factors");Out.Ln |
||
END Factors. |
END Factors. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,404: | Line 4,404: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">use IO; |
||
use Structure; |
use Structure; |
||
Line 4,441: | Line 4,441: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let rec range = function 0 -> [] | n -> range(n-1) @ [n] |
||
let factors n = |
let factors n = |
||
List.filter (fun v -> (n mod v) = 0) (range n)</ |
List.filter (fun v -> (n mod v) = 0) (range n)</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">Integer method: factors self seq filter(#[ self isMultiple ]) ; |
||
120 factors println</ |
120 factors println</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,461: | Line 4,461: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {Factors N} |
fun {Factors N} |
||
Sqr = {Float.toInt {Sqrt {Int.toFloat N}}} |
Sqr = {Float.toInt {Sqrt {Int.toFloat N}}} |
||
Line 4,480: | Line 4,480: | ||
end |
end |
||
in |
in |
||
{Show {Factors 53}}</ |
{Show {Factors 53}}</syntaxhighlight> |
||
=={{header|Panda}}== |
=={{header|Panda}}== |
||
Panda has a factor function already, it's defined as: |
Panda has a factor function already, it's defined as: |
||
< |
<syntaxhighlight lang="panda">fun factor(n) type integer->integer |
||
f where n.mod(1..n=>f)==0 |
f where n.mod(1..n=>f)==0 |
||
45.factor</ |
45.factor</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
<lang |
<syntaxhighlight lang="parigp">divisors(n)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{trans|Fortran}} |
{{trans|Fortran}} |
||
{{works with|Free Pascal|2.6.2}} |
{{works with|Free Pascal|2.6.2}} |
||
< |
<syntaxhighlight lang="pascal">program Factors; |
||
var |
var |
||
i, number: integer; |
i, number: integer; |
||
Line 4,513: | Line 4,513: | ||
write(i, number/i); |
write(i, number/i); |
||
writeln; |
writeln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,529: | Line 4,529: | ||
"runtime overhead" +25% instead +100% for quicksort against no sort.<BR> |
"runtime overhead" +25% instead +100% for quicksort against no sort.<BR> |
||
Especially fast for consecutive integers. |
Especially fast for consecutive integers. |
||
< |
<syntaxhighlight lang="pascal">program FacOfInt; |
||
// gets factors of consecutive integers fast |
// gets factors of consecutive integers fast |
||
// limited to 1.2e11 |
// limited to 1.2e11 |
||
Line 5,007: | Line 5,007: | ||
AllFacsOut(Divs,true); |
AllFacsOut(Divs,true); |
||
AllFacsOut(Divs,false); |
AllFacsOut(Divs,false); |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,032: | Line 5,032: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">sub factors |
||
{ |
{ |
||
my($n) = @_; |
my($n) = @_; |
||
return grep { $n % $_ == 0 }(1 .. $n); |
return grep { $n % $_ == 0 }(1 .. $n); |
||
} |
} |
||
print join ' ',factors(64), "\n";</ |
print join ' ',factors(64), "\n";</syntaxhighlight> |
||
Or more intelligently: |
Or more intelligently: |
||
< |
<syntaxhighlight lang="perl">sub factors { |
||
my $n = shift; |
my $n = shift; |
||
$n = -$n if $n < 0; |
$n = -$n if $n < 0; |
||
Line 5,051: | Line 5,051: | ||
@divisors, map { $_*$_ == $n ? () : int($n/$_) } reverse @divisors; |
@divisors, map { $_*$_ == $n ? () : int($n/$_) } reverse @divisors; |
||
} |
} |
||
print join " ", factors(64), "\n";</ |
print join " ", factors(64), "\n";</syntaxhighlight> |
||
One could also use a module, e.g.: |
One could also use a module, e.g.: |
||
{{libheader|ntheory}} |
{{libheader|ntheory}} |
||
< |
<syntaxhighlight lang="perl">use ntheory qw/divisors/; |
||
print join " ", divisors(12345678), "\n"; |
print join " ", divisors(12345678), "\n"; |
||
# Alternately something like: fordivisors { say } 12345678; </ |
# Alternately something like: fordivisors { say } 12345678; </syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
There is a builtin factors(n), which takes an optional second parameter to include 1 and n: |
There is a builtin factors(n), which takes an optional second parameter to include 1 and n: |
||
<!--< |
<!--<syntaxhighlight lang="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> |
<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,071: | Line 5,071: | ||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Factors_of_an_integer |
||
by Galileo, 05/2022 #/ |
by Galileo, 05/2022 #/ |
||
Line 5,087: | Line 5,087: | ||
96 factors |
96 factors |
||
pstack</ |
pstack</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,095: | Line 5,095: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function GetFactors($n){ |
||
$factors = array(1, $n); |
$factors = array(1, $n); |
||
for($i = 2; $i * $i <= $n; $i++){ |
for($i = 2; $i * $i <= $n; $i++){ |
||
Line 5,106: | Line 5,106: | ||
sort($factors); |
sort($factors); |
||
return $factors; |
return $factors; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
===List comprehension=== |
===List comprehension=== |
||
< |
<syntaxhighlight lang="picat">factors(N) = [[D,N // D] : D in 1..N.sqrt.floor, N mod D == 0].flatten.sort_remove_dups.</syntaxhighlight> |
||
===Recursion=== |
===Recursion=== |
||
{{trans|Prolog}} |
{{trans|Prolog}} |
||
< |
<syntaxhighlight lang="picat">factors2(N,Fs) :- |
||
integer(N), |
integer(N), |
||
N > 0, |
N > 0, |
||
Line 5,123: | Line 5,123: | ||
between(1,L,X), |
between(1,L,X), |
||
0 == N mod X, |
0 == N mod X, |
||
( F = X ; F = N // X ).</ |
( F = X ; F = N // X ).</syntaxhighlight> |
||
===Loop using set=== |
===Loop using set=== |
||
< |
<syntaxhighlight lang="picat">factors3(N) = Set.keys.sort => |
||
Set = new_set(), |
Set = new_set(), |
||
Set.put(1), |
Set.put(1), |
||
Line 5,133: | Line 5,133: | ||
Set.put(I), |
Set.put(I), |
||
Set.put(N//I) |
Set.put(N//I) |
||
end.</ |
end.</syntaxhighlight> |
||
===Comparison=== |
===Comparison=== |
||
Let's compare with 18! (6402373705728000) which has 14688 factors. The recursive version is slightly faster than the loop + set version. |
Let's compare with 18! (6402373705728000) which has 14688 factors. The recursive version is slightly faster than the loop + set version. |
||
< |
<syntaxhighlight lang="picat">go => |
||
N = 6402373705728000, % factorial(18), |
N = 6402373705728000, % factorial(18), |
||
println("factors:"), |
println("factors:"), |
||
Line 5,145: | Line 5,145: | ||
println("factors3:"), |
println("factors3:"), |
||
time(Fs3=factors3(N)).len), |
time(Fs3=factors3(N)).len), |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 5,162: | Line 5,162: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de factors (N) |
||
(filter |
(filter |
||
'((D) (=0 (% N D))) |
'((D) (=0 (% N D))) |
||
(range 1 N) ) )</ |
(range 1 N) ) )</syntaxhighlight> |
||
=={{header|PILOT}}== |
=={{header|PILOT}}== |
||
< |
<syntaxhighlight lang="pilot">T :Enter a number. |
||
A :#n |
A :#n |
||
C :factor = 1 |
C :factor = 1 |
||
Line 5,179: | Line 5,179: | ||
J :*Loop |
J :*Loop |
||
*Finished |
*Finished |
||
END:</ |
END:</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">factors: procedure options(main); |
||
declare i binary( 15 )fixed; |
declare i binary( 15 )fixed; |
||
declare n binary( 15 )fixed; |
declare n binary( 15 )fixed; |
||
Line 5,192: | Line 5,192: | ||
end; |
end; |
||
end factors; |
end factors; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 5,216: | Line 5,216: | ||
=={{header|Plain English}}== |
=={{header|Plain English}}== |
||
< |
<syntaxhighlight lang="plainenglish">To run: |
||
Start up. |
Start up. |
||
Show the factors of 11. |
Show the factors of 11. |
||
Line 5,237: | Line 5,237: | ||
To show a factor and another factor: |
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. |
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.</ |
Write "" then the factor on the console without advancing.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,254: | Line 5,254: | ||
The PL/I include file "pg.inc" can be found on the [[Polyglot:PL/I and PL/M]] page. |
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. |
Note the use of text in column 81 onwards to hide the PL/I specifics from the PL/M compiler. |
||
< |
<syntaxhighlight lang="pli">factors_100H: procedure options (main); |
||
/* PL/I DEFINITIONS */ |
/* PL/I DEFINITIONS */ |
||
Line 5,296: | Line 5,296: | ||
CALL PRNL; |
CALL PRNL; |
||
END; |
END; |
||
EOF: end factors_100H;</ |
EOF: end factors_100H;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,314: | Line 5,314: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
===Straightforward but slow=== |
===Straightforward but slow=== |
||
< |
<syntaxhighlight lang="powershell">function Get-Factor ($a) { |
||
1..$a | Where-Object { $a % $_ -eq 0 } |
1..$a | Where-Object { $a % $_ -eq 0 } |
||
}</ |
}</syntaxhighlight> |
||
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. |
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=== |
===A little more clever=== |
||
< |
<syntaxhighlight lang="powershell">function Get-Factor ($a) { |
||
1..[Math]::Sqrt($a) ` |
1..[Math]::Sqrt($a) ` |
||
| Where-Object { $a % $_ -eq 0 } ` |
| Where-Object { $a % $_ -eq 0 } ` |
||
| ForEach-Object { $_; $a / $_ } ` |
| ForEach-Object { $_; $a / $_ } ` |
||
| Sort-Object -Unique |
| Sort-Object -Unique |
||
}</ |
}</syntaxhighlight> |
||
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. |
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}}== |
=={{header|ProDOS}}== |
||
Uses the math module: |
Uses the math module: |
||
< |
<syntaxhighlight lang="prodos">editvar /newvar /value=a /userinput=1 /title=Enter an integer: |
||
do /delimspaces %% -a- >b |
do /delimspaces %% -a- >b |
||
printline Factors of -a-: -b- </ |
printline Factors of -a-: -b- </syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
'''Simple Brute Force Implementation''' |
'''Simple Brute Force Implementation''' |
||
<syntaxhighlight lang="prolog"> |
|||
<lang Prolog> |
|||
brute_force_factors( N , Fs ) :- |
brute_force_factors( N , Fs ) :- |
||
integer(N) , |
integer(N) , |
||
Line 5,342: | Line 5,342: | ||
setof( F , ( between(1,N,F) , N mod F =:= 0 ) , Fs ) |
setof( F , ( between(1,N,F) , N mod F =:= 0 ) , Fs ) |
||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''A Slightly Smarter Implementation''' |
'''A Slightly Smarter Implementation''' |
||
<syntaxhighlight lang="prolog"> |
|||
<lang Prolog> |
|||
smart_factors(N,Fs) :- |
smart_factors(N,Fs) :- |
||
integer(N) , |
integer(N) , |
||
Line 5,358: | Line 5,358: | ||
( F = X ; F is N // X ) |
( F = X ; F is N // X ) |
||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Not every Prolog has <code>between/3</code>: you might need this: |
Not every Prolog has <code>between/3</code>: you might need this: |
||
<syntaxhighlight lang="prolog"> |
|||
<lang Prolog> |
|||
between(X,Y,Z) :- |
between(X,Y,Z) :- |
||
Line 5,379: | Line 5,379: | ||
between1(X1,Y,Z) |
between1(X1,Y,Z) |
||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 5,413: | Line 5,413: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure PrintFactors(n) |
||
Protected i, lim=Round(sqr(n),#PB_Round_Up) |
Protected i, lim=Round(sqr(n),#PB_Round_Up) |
||
NewList F.i() |
NewList F.i() |
||
Line 5,433: | Line 5,433: | ||
PrintFactors(Val(Input())) |
PrintFactors(Val(Input())) |
||
Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input() |
Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,443: | Line 5,443: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
Naive and slow but simplest (check all numbers from 1 to n): |
Naive and slow but simplest (check all numbers from 1 to n): |
||
< |
<syntaxhighlight lang="python">>>> def factors(n): |
||
return [i for i in range(1, n + 1) if not n%i]</ |
return [i for i in range(1, n + 1) if not n%i]</syntaxhighlight> |
||
Slightly better (realize that there are no factors between n/2 and n): |
Slightly better (realize that there are no factors between n/2 and n): |
||
< |
<syntaxhighlight lang="python">>>> def factors(n): |
||
return [i for i in range(1, n//2 + 1) if not n%i] + [n] |
return [i for i in range(1, n//2 + 1) if not n%i] + [n] |
||
>>> factors(45) |
>>> factors(45) |
||
[1, 3, 5, 9, 15, 45]</ |
[1, 3, 5, 9, 15, 45]</syntaxhighlight> |
||
Much better (realize that factors come in pairs, the smaller of which is no bigger than sqrt(n)): |
Much better (realize that factors come in pairs, the smaller of which is no bigger than sqrt(n)): |
||
< |
<syntaxhighlight lang="python">>>> from math import sqrt |
||
>>> def factor(n): |
>>> def factor(n): |
||
factors = set() |
factors = set() |
||
Line 5,467: | Line 5,467: | ||
45: factors: [1, 3, 5, 9, 15, 45] |
45: factors: [1, 3, 5, 9, 15, 45] |
||
53: factors: [1, 53] |
53: factors: [1, 53] |
||
64: factors: [1, 2, 4, 8, 16, 32, 64]</ |
64: factors: [1, 2, 4, 8, 16, 32, 64]</syntaxhighlight> |
||
More efficient when factoring many numbers: |
More efficient when factoring many numbers: |
||
< |
<syntaxhighlight lang="python">from itertools import chain, cycle, accumulate # last of which is Python 3 only |
||
def factors(n): |
def factors(n): |
||
Line 5,487: | Line 5,487: | ||
for e in prime_powers(n): |
for e in prime_powers(n): |
||
r += [a*b for a in r for b in e] |
r += [a*b for a in r for b in e] |
||
return r</ |
return r</syntaxhighlight> |
||
<syntaxhighlight lang="qb64"> |
|||
<lang QB64> |
|||
'Task |
'Task |
||
'Compute the factors of a positive integer. |
'Compute the factors of a positive integer. |
||
Line 5,504: | Line 5,504: | ||
Wend |
Wend |
||
End |
End |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 5,512: | Line 5,512: | ||
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. |
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. |
||
<lang> [ 1 |
<syntaxhighlight lang="text"> [ 1 |
||
[ 2dup < not while |
[ 2dup < not while |
||
2 << again ] |
2 << again ] |
||
Line 5,544: | Line 5,544: | ||
factors witheach |
factors witheach |
||
[ echo i if say ", " ] |
[ echo i if say ", " ] |
||
cr ]</ |
cr ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,572: | Line 5,572: | ||
=={{header|R}}== |
=={{header|R}}== |
||
===Array solution=== |
===Array solution=== |
||
< |
<syntaxhighlight lang="rsplus">factors <- function(n) |
||
{ |
{ |
||
if(length(n) > 1) |
if(length(n) > 1) |
||
Line 5,582: | Line 5,582: | ||
one.to.n[(n %% one.to.n) == 0] |
one.to.n[(n %% one.to.n) == 0] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,597: | Line 5,597: | ||
===Filter solution=== |
===Filter solution=== |
||
With identical output, a more idiomatic way is to use R's Filter. |
With identical output, a more idiomatic way is to use R's Filter. |
||
< |
<syntaxhighlight 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. |
#Vectorize is an interesting alternative to the previous solution's lapply. |
||
manyFactors <- function(vec) Vectorize(factors)(vec)</ |
manyFactors <- function(vec) Vectorize(factors)(vec)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
#lang racket |
#lang racket |
||
Line 5,633: | Line 5,633: | ||
(time (length (divisors huge))) |
(time (length (divisors huge))) |
||
;; And this one clocks at 17ms |
;; And this one clocks at 17ms |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{works with|Rakudo|2015.12}} |
{{works with|Rakudo|2015.12}} |
||
<lang |
<syntaxhighlight lang="raku" line>sub factors (Int $n) { (1..$n).grep($n %% *) }</syntaxhighlight> |
||
=={{header|REALbasic}}== |
=={{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 |
'This function accepts an unsigned 64 bit integer as input and returns an array of unsigned 64 bit integers |
||
Dim result() As UInt64 |
Dim result() As UInt64 |
||
Line 5,653: | Line 5,653: | ||
result.Append(num) 'Since a given number is always a factor of itself |
result.Append(num) 'Since a given number is always a factor of itself |
||
Return result |
Return result |
||
End Function</ |
End Function</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="red">Red [] |
||
factors: function [n [integer!]] [ |
factors: function [n [integer!]] [ |
||
Line 5,679: | Line 5,679: | ||
][ |
][ |
||
print mold/flat sort factors num |
print mold/flat sort factors num |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Relation}}== |
=={{header|Relation}}== |
||
<syntaxhighlight lang="relation"> |
|||
<lang Relation> |
|||
program factors(num) |
program factors(num) |
||
relation fact |
relation fact |
||
Line 5,696: | Line 5,696: | ||
print |
print |
||
end program |
end program |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 5,709: | Line 5,709: | ||
This REXX version is about '''22%''' faster than the alternate REXX version (2<sup>nd</sup> version). |
This REXX version is about '''22%''' faster than the alternate REXX version (2<sup>nd</sup> version). |
||
< |
<syntaxhighlight lang="rexx">/*REXX program displays divisors of any [negative/zero/positive] integer or a range.*/ |
||
parse arg LO HI inc . /*obtain the optional args*/ |
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*/ |
HI= word(HI LO 20, 1); LO= word(LO 1,1); inc= word(inc 1,1) /*define the range options*/ |
||
Line 5,737: | Line 5,737: | ||
end /*j*/ /* [↑] % ≡ integer division. ___*/ |
end /*j*/ /* [↑] % ≡ integer division. ___*/ |
||
if sq.j==x then return a j b /*Was X a square? Then insert √ x */ |
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. */</ |
return a b /*return the divisors of both lists. */</syntaxhighlight> |
||
{{out|output|text= when using the input of: <tt> -6 200 </tt>}} |
{{out|output|text= when using the input of: <tt> -6 200 </tt>}} |
||
Line 5,957: | Line 5,957: | ||
===Alternate Version=== |
===Alternate Version=== |
||
{{trans|REXX optimized version}} |
{{trans|REXX optimized version}} |
||
< |
<syntaxhighlight lang="rexx">/* REXX *************************************************************** |
||
* Program to calculate and show divisors of positive integer(s). |
* Program to calculate and show divisors of positive integer(s). |
||
* 03.08.2012 Walter Pachl simplified the above somewhat |
* 03.08.2012 Walter Pachl simplified the above somewhat |
||
Line 5,988: | Line 5,988: | ||
If j*j=x Then /*for a square number as input */ |
If j*j=x Then /*for a square number as input */ |
||
lo=lo j /* add its square root */ |
lo=lo j /* add its square root */ |
||
return lo hi /* return both lists */</ |
return lo hi /* return both lists */</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
Line 6,196: | Line 6,196: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
nArray = list(100) |
nArray = list(100) |
||
n = 45 |
n = 45 |
||
Line 6,208: | Line 6,208: | ||
see "" + nArray[i] + " " |
see "" + nArray[i] + " " |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">class Integer |
||
def factors() (1..self).select { |n| (self % n).zero? } end |
def factors() (1..self).select { |n| (self % n).zero? } end |
||
end |
end |
||
p 45.factors</ |
p 45.factors</syntaxhighlight> |
||
[1, 3, 5, 9, 15, 45] |
[1, 3, 5, 9, 15, 45] |
||
As we only have to loop up to <math>\sqrt{n}</math>, we can write |
As we only have to loop up to <math>\sqrt{n}</math>, we can write |
||
< |
<syntaxhighlight lang="ruby">class Integer |
||
def factors |
def factors |
||
1.upto(Integer.sqrt(self)).select {|i| (self % i).zero?}.inject([]) do |f, i| |
1.upto(Integer.sqrt(self)).select {|i| (self % i).zero?}.inject([]) do |f, i| |
||
Line 6,226: | Line 6,226: | ||
end |
end |
||
end |
end |
||
[45, 53, 64].each {|n| puts "#{n} : #{n.factors}"}</ |
[45, 53, 64].each {|n| puts "#{n} : #{n.factors}"}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,234: | Line 6,234: | ||
===Using the prime library=== |
===Using the prime library=== |
||
< |
<syntaxhighlight lang="ruby"> |
||
require 'prime' |
require 'prime' |
||
Line 6,247: | Line 6,247: | ||
[1, 7, 45, 100].each{|n| p factors n} |
[1, 7, 45, 100].each{|n| p factors n} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 6,257: | Line 6,257: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">PRINT "Factors of 45 are ";factorlist$(45) |
||
PRINT "Factors of 12345 are "; factorlist$(12345) |
PRINT "Factors of 12345 are "; factorlist$(12345) |
||
END |
END |
||
Line 6,288: | Line 6,288: | ||
factorlist$ = factorlist$ + STR$(L(i)) + ", " |
factorlist$ = factorlist$ + STR$(L(i)) + ", " |
||
NEXT |
NEXT |
||
end function</ |
end function</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,296: | Line 6,296: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight 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, 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)); |
assert_eq!(vec![1, 101], factor(101)); |
||
Line 6,313: | Line 6,313: | ||
factors.sort(); // sorts the factors into numerical order for viewing purposes |
factors.sort(); // sorts the factors into numerical order for viewing purposes |
||
factors // returns the factors |
factors // returns the factors |
||
}</ |
}</syntaxhighlight> |
||
Alternative functional version: |
Alternative functional version: |
||
< |
<syntaxhighlight lang="rust"> |
||
fn factor(n: i32) -> Vec<i32> { |
fn factor(n: i32) -> Vec<i32> { |
||
(1..=n).filter(|i| n % i == 0).collect() |
(1..=n).filter(|i| n % i == 0).collect() |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
factors!(n :INT):INT is |
factors!(n :INT):INT is |
||
Line 6,351: | Line 6,351: | ||
end; |
end; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Brute force approach: |
Brute force approach: |
||
< |
<syntaxhighlight lang="scala">def factors(num: Int) = { |
||
(1 to num).filter { divisor => |
(1 to num).filter { divisor => |
||
num % divisor == 0 |
num % divisor == 0 |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Brute force until sqrt(num) is enough, the code above can be edited as follows (Scala 3 enabled) |
Brute force until sqrt(num) is enough, the code above can be edited as follows (Scala 3 enabled) |
||
< |
<syntaxhighlight lang="scala">def factors(num: Int) = { |
||
val list = (1 to math.sqrt(num).floor.toInt).filter(num % _ == 0) |
val list = (1 to math.sqrt(num).floor.toInt).filter(num % _ == 0) |
||
list ++ list.reverse.dropWhile(d => d*d == num).map(num / _) |
list ++ list.reverse.dropWhile(d => d*d == num).map(num / _) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
This implementation uses a naive trial division algorithm. |
This implementation uses a naive trial division algorithm. |
||
< |
<syntaxhighlight lang="scheme">(define (factors n) |
||
(define (*factors d) |
(define (*factors d) |
||
(cond ((> d n) (list)) |
(cond ((> d n) (list)) |
||
Line 6,376: | Line 6,376: | ||
(display (factors 1111111)) |
(display (factors 1111111)) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,384: | Line 6,384: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: writeFactors (in integer: number) is func |
const proc: writeFactors (in integer: number) is func |
||
Line 6,413: | Line 6,413: | ||
writeFactors(number); |
writeFactors(number); |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,426: | Line 6,426: | ||
A simple brute force method using an indexed partial function as a filter. |
A simple brute force method using an indexed partial function as a filter. |
||
< |
<syntaxhighlight lang="sequencel">Factors(num(0))[i] := i when num mod i = 0 foreach i within 1 ... num;</syntaxhighlight> |
||
'''Slightly More Efficient Method''' |
'''Slightly More Efficient Method''' |
||
A slightly more efficient method, only going up to the sqrt(n). |
A slightly more efficient method, only going up to the sqrt(n). |
||
< |
<syntaxhighlight lang="sequencel">Factors(num(0)) := |
||
let |
let |
||
factorPairs[i] := |
factorPairs[i] := |
||
Line 6,439: | Line 6,439: | ||
foreach i within 1 ... floor(sqrt(num)); |
foreach i within 1 ... floor(sqrt(num)); |
||
in |
in |
||
join(factorPairs);</ |
join(factorPairs);</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Built-in: |
Built-in: |
||
< |
<syntaxhighlight lang="ruby">say divisors(97) #=> [1, 97] |
||
say divisors(2695) #=> [1, 5, 7, 11, 35, 49, 55, 77, 245, 385, 539, 2695]</ |
say divisors(2695) #=> [1, 5, 7, 11, 35, 49, 55, 77, 245, 385, 539, 2695]</syntaxhighlight> |
||
Trial-division (slow for large n): |
Trial-division (slow for large n): |
||
< |
<syntaxhighlight lang="ruby">func divisors(n) { |
||
gather { |
gather { |
||
{ |d| |
{ |d| |
||
Line 6,458: | Line 6,458: | ||
[53, 64, 32766].each {|n| |
[53, 64, 32766].each {|n| |
||
say "divisors(#{n}): #{divisors(n)}" |
say "divisors(#{n}): #{divisors(n)}" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,467: | Line 6,467: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">n@(Integer traits) primeFactors |
||
[ |
[ |
||
[| :result | |
[| :result | |
||
result nextPut: 1. |
result nextPut: 1. |
||
n primesDo: [| :prime | result nextPut: prime]] writingAs: {} |
n primesDo: [| :prime | result nextPut: prime]] writingAs: {} |
||
].</ |
].</syntaxhighlight> |
||
where <tt>primesDo:</tt> is a part of the standard numerics library: |
where <tt>primesDo:</tt> is a part of the standard numerics library: |
||
< |
<syntaxhighlight lang="slate">n@(Integer traits) primesDo: block |
||
"Decomposes the Integer into primes, applying the block to each (in increasing |
"Decomposes the Integer into primes, applying the block to each (in increasing |
||
order)." |
order)." |
||
Line 6,488: | Line 6,488: | ||
[div: next. |
[div: next. |
||
next: next + 2] "Just looks at the next odd integer." |
next: next + 2] "Just looks at the next odd integer." |
||
].</ |
].</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 6,494: | Line 6,494: | ||
Copied from the Python example, but code added to the Integer built in class: |
Copied from the Python example, but code added to the Integer built in class: |
||
< |
<syntaxhighlight lang="smalltalk">Integer>>factors |
||
| a | |
| a | |
||
a := OrderedCollection new. |
a := OrderedCollection new. |
||
Line 6,500: | Line 6,500: | ||
((self \\ i) = 0) ifTrue: [ a add: i ] ]. |
((self \\ i) = 0) ifTrue: [ a add: i ] ]. |
||
a add: self. |
a add: self. |
||
^a</ |
^a</syntaxhighlight> |
||
Then use as follows: |
Then use as follows: |
||
< |
<syntaxhighlight lang="smalltalk"> |
||
59 factors -> an OrderedCollection(1 59) |
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) |
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}}== |
=={{header|Standard ML}}== |
||
Need to print the list because Standard ML truncates the display of |
Need to print the list because Standard ML truncates the display of |
||
longer returned lists. |
longer returned lists. |
||
< |
<syntaxhighlight lang="standard ml">fun printIntList ls = |
||
( |
( |
||
List.app (fn n => print(Int.toString n ^ " ")) ls; |
List.app (fn n => print(Int.toString n ^ " ")) ls; |
||
Line 6,530: | Line 6,530: | ||
factors'(n,1) |
factors'(n,1) |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Call: |
Call: |
||
< |
<syntaxhighlight lang="standard ml">printIntList(factors 12345) |
||
printIntList(factors 120)</ |
printIntList(factors 120)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 3 5 15 823 2469 4115 12345 |
<pre>1 3 5 15 823 2469 4115 12345 |
||
Line 6,541: | Line 6,541: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
Simple implementation: |
Simple implementation: |
||
< |
<syntaxhighlight lang="swift">func factors(n: Int) -> [Int] { |
||
return filter(1...n) { n % $0 == 0 } |
return filter(1...n) { n % $0 == 0 } |
||
}</ |
}</syntaxhighlight> |
||
More efficient implementation: |
More efficient implementation: |
||
< |
<syntaxhighlight lang="swift">import func Darwin.sqrt |
||
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) } |
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) } |
||
Line 6,563: | Line 6,563: | ||
return sorted(result) |
return sorted(result) |
||
}</ |
}</syntaxhighlight> |
||
Call: |
Call: |
||
< |
<syntaxhighlight lang="swift">println(factors(4)) |
||
println(factors(1)) |
println(factors(1)) |
||
println(factors(25)) |
println(factors(25)) |
||
println(factors(63)) |
println(factors(63)) |
||
println(factors(19)) |
println(factors(19)) |
||
println(factors(768))</ |
println(factors(768))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1, 2, 4] |
<pre>[1, 2, 4] |
||
Line 6,581: | Line 6,581: | ||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
< |
<syntaxhighlight lang="tailspin"> |
||
[1..351 -> \(when <?(351 mod $ <=0>)> do $! \)] -> !OUT::write |
[1..351 -> \(when <?(351 mod $ <=0>)> do $! \)] -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,590: | Line 6,590: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">proc factors {n} { |
||
set factors {} |
set factors {} |
||
for {set i 1} {$i <= sqrt($n)} {incr i} { |
for {set i 1} {$i <= sqrt($n)} {incr i} { |
||
Line 6,601: | Line 6,601: | ||
puts [factors 64] |
puts [factors 64] |
||
puts [factors 45] |
puts [factors 45] |
||
puts [factors 53]</ |
puts [factors 53]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,611: | Line 6,611: | ||
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>. |
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>. |
||
<lang>factor() { |
<syntaxhighlight lang="text">factor() { |
||
r=`echo "sqrt($1)" | bc` # or `echo $1 v p | dc` |
r=`echo "sqrt($1)" | bc` # or `echo $1 v p | dc` |
||
i=1 |
i=1 |
||
Line 6,622: | Line 6,622: | ||
done | sort -nu |
done | sort -nu |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
This program takes an integer from the command line and outputs its factors. |
This program takes an integer from the command line and outputs its factors. |
||
< |
<syntaxhighlight lang="ursa">decl int n |
||
set n (int args<1>) |
set n (int args<1>) |
||
Line 6,635: | Line 6,635: | ||
end if |
end if |
||
end for |
end for |
||
out n endl console</ |
out n endl console</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
The simple way: |
The simple way: |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#import nat |
#import nat |
||
factors "n" = (filter not remainder/"n") nrange(1,"n")</ |
factors "n" = (filter not remainder/"n") nrange(1,"n")</syntaxhighlight> |
||
The complicated way: |
The complicated way: |
||
< |
<syntaxhighlight lang="ursala">factors "n" = nleq-<&@s <.~&r,quotient>*= "n"-* (not remainder/"n")*~ nrange(1,root("n",2))</syntaxhighlight> |
||
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 |
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 |
||
< |
<syntaxhighlight lang="ursala">factors = nleq-<&@rrZPFLs+ ^(~&r,division)^*D/~& nrange/1+ &!*K31</syntaxhighlight> |
||
where <code>nleq-<&</code> isn't strictly necessary unless an ordered list is required. |
where <code>nleq-<&</code> isn't strictly necessary unless an ordered list is required. |
||
< |
<syntaxhighlight lang="ursala">#cast %nL |
||
example = factors 100</ |
example = factors 100</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,656: | Line 6,656: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Function Factors(x As Integer) As String |
||
Application.Volatile |
Application.Volatile |
||
Dim i As Integer |
Dim i As Integer |
||
Line 6,669: | Line 6,669: | ||
Next i |
Next i |
||
If x <> 1 Then Factors = Factors & ", " & corresponding_factors |
If x <> 1 Then Factors = Factors & ", " & corresponding_factors |
||
End Function</ |
End Function</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>cell formula is "=Factors(840)" |
<pre>cell formula is "=Factors(840)" |
||
Line 6,676: | Line 6,676: | ||
=={{header|Verilog}}== |
=={{header|Verilog}}== |
||
<syntaxhighlight lang="verilog"> |
|||
<lang Verilog> |
|||
module main; |
module main; |
||
integer i, n; |
integer i, n; |
||
Line 6,689: | Line 6,689: | ||
end |
end |
||
endmodule |
endmodule |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,697: | Line 6,697: | ||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<syntaxhighlight lang="wortel">@let { |
||
factors1 &n !-\%%n @to n |
factors1 &n !-\%%n @to n |
||
factors_tacit @(\\%% !- @to) |
factors_tacit @(\\%% !- @to) |
||
Line 6,705: | Line 6,705: | ||
!factors1 720 |
!factors1 720 |
||
]] |
]] |
||
}</ |
}</syntaxhighlight> |
||
Returns: <pre>[ |
Returns: <pre>[ |
||
[1 2 5 10] |
[1 2 5 10] |
||
Line 6,715: | Line 6,715: | ||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
{{libheader|Wren-math}} |
{{libheader|Wren-math}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt |
||
import "/math" for Int |
import "/math" for Int |
||
var a = [11, 21, 32, 45, 67, 96, 159, 723, 1024, 5673, 12345, 32767, 123459, 999997] |
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:") |
System.print("The factors of the following numbers are:") |
||
for (e in a) System.print("%(Fmt.d(6, e)) => %(Int.divisors(e))")</ |
for (e in a) System.print("%(Fmt.d(6, e)) => %(Int.divisors(e))")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,742: | Line 6,742: | ||
=={{header|X86 Assembly}}== |
=={{header|X86 Assembly}}== |
||
{{works with|nasm}} |
{{works with|nasm}} |
||
< |
<syntaxhighlight lang="asm"> |
||
section .bss |
section .bss |
||
factorArr resd 250 ;big buffer against seg fault |
factorArr resd 250 ;big buffer against seg fault |
||
Line 6,775: | Line 6,775: | ||
mov esp, ebp ;garbage collecting |
mov esp, ebp ;garbage collecting |
||
ret |
ret |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
int N0, N, F; |
int N0, N, F; |
||
[N0:= 1; |
[N0:= 1; |
||
Line 6,794: | Line 6,794: | ||
N0:= N0+1; |
N0:= N0+1; |
||
until KeyHit; |
until KeyHit; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,833: | Line 6,833: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="yabasic"> |
||
sub printFactors(n) |
sub printFactors(n) |
||
if n < 1 then return 0 : fi |
if n < 1 then return 0 : fi |
||
Line 6,851: | Line 6,851: | ||
print |
print |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,860: | Line 6,860: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|Chapel}} |
{{trans|Chapel}} |
||
< |
<syntaxhighlight lang="zkl">fcn f(n){ (1).pump(n.toFloat().sqrt(), List, |
||
'wrap(m){((n % m)==0) and T(m,n/m) or Void.Skip}) } |
'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</ |
fcn g(n){ [[(m); [1..n.toFloat().sqrt()],'{n%m==0}; '{T(m,n/m)} ]] } // list comprehension</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,874: | Line 6,874: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
{{trans|AWK}} |
{{trans|AWK}} |
||
< |
<syntaxhighlight lang="zxbasic">10 INPUT "Enter a number or 0 to exit: ";n |
||
20 IF n=0 THEN STOP |
20 IF n=0 THEN STOP |
||
30 PRINT "Factors of ";n;": "; |
30 PRINT "Factors of ";n;": "; |
||
Line 6,880: | Line 6,880: | ||
50 IF FN m(n,i)=0 THEN PRINT i;" "; |
50 IF FN m(n,i)=0 THEN PRINT i;" "; |
||
60 NEXT i |
60 NEXT i |
||
70 DEF FN m(a,b)=a-INT (a/b)*b</ |
70 DEF FN m(a,b)=a-INT (a/b)*b</syntaxhighlight> |