Count in factors: Difference between revisions

Add Refal
(Add Refal)
(112 intermediate revisions by 52 users not shown)
Line 1:
{{task|Prime Numbers}}
{{task|Prime Numbers}}Write a program which counts up from 1, displaying each number as the multiplication of its prime factors. For the purpose of this task, <math>1</math> may be shown as itself.
 
;Task:
For example, <math>2</math> is prime, so it would be shown as itself. <math>6</math> is not prime; it would be shown as <math>2\times3</math>. Likewise, 2144 is not prime; it would be shown as <math>2\times2\times2\times2\times2\times67</math>.
Write a program which counts up from &nbsp; '''1''', &nbsp; displaying each number as the multiplication of its prime factors.
 
For the purpose of this task, &nbsp; '''1''' &nbsp; (unity) &nbsp; may be shown as itself.
c.f. [[Prime decomposition]]
 
 
;Example:
&nbsp; &nbsp; &nbsp; '''2''' &nbsp; is prime, &nbsp; so it would be shown as itself.
<br>&nbsp; &nbsp; &nbsp; '''6''' &nbsp; is not prime; &nbsp; it would be shown as &nbsp; '''<math>2\times3</math>.'''
<br>'''2144''' &nbsp; is not prime; &nbsp; it would be shown as &nbsp; '''<math>2\times2\times2\times2\times2\times67</math>.'''
 
 
;Related tasks:
* &nbsp; [[prime decomposition]]
* &nbsp; [[factors of an integer]]
* &nbsp; [[Sieve of Eratosthenes]]
* &nbsp; [[primality by trial division]]
* &nbsp; [[factors of a Mersenne number]]
* &nbsp; [[trial factoring of a Mersenne number]]
* &nbsp; [[partition an integer X into N primes]]
<br><br>
 
=={{header|11l}}==
{{trans|C++}}<syntaxhighlight lang="11l">F get_prime_factors(=li)
I li == 1
R ‘1’
E
V res = ‘’
V f = 2
L
I li % f == 0
res ‘’= f
li /= f
I li == 1
L.break
res ‘’= ‘ x ’
E
f++
R res
 
L(x) 1..17
print(‘#4: #.’.format(x, get_prime_factors(x)))
print(‘2144: ’get_prime_factors(2144))</syntaxhighlight>
 
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2 x 2
5: 5
6: 2 x 3
7: 7
8: 2 x 2 x 2
9: 3 x 3
10: 2 x 5
11: 11
12: 2 x 2 x 3
13: 13
14: 2 x 7
15: 3 x 5
16: 2 x 2 x 2 x 2
17: 17
2144: 2 x 2 x 2 x 2 x 2 x 67
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Count in factors 24/03/2017
COUNTFAC CSECT assist plig\COUNTFAC
USING COUNTFAC,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
L R6,=F'1' i=1
DO WHILE=(C,R6,LE,=F'40') do i=1 to 40
LR R7,R6 n=i
MVI F,X'01' f=true
MVC PG,=CL80' ' clear buffer
LA R10,PG pgi=0
XDECO R6,XDEC edit i
MVC 0(12,R10),XDEC output i
LA R10,12(R10) pgi=pgi+12
MVC 0(1,R10),=C'=' output '='
LA R10,1(R10) pgi=pgi+1
IF C,R7,EQ,=F'1' THEN if n=1 then
MVI 0(R10),C'1' output n
ELSE , else
LA R8,2 p=2
DO WHILE=(CR,R8,LE,R7) do while p<=n
LR R4,R7 n
SRDA R4,32 ~
DR R4,R8 /p
IF LTR,R4,Z,R4 THEN if n//p=0 then
IF CLI,F,EQ,X'00' THEN if not f then
MVC 0(1,R10),=C'*' output '*'
LA R10,1(R10) pgi=pgi+1
ELSE , else
MVI F,X'00' f=false
ENDIF , endif
CVD R8,PP convert bin p to packed pp
MVC WORK12,MASX12 in fact L13
EDMK WORK12,PP+2 edit and mark
LA R9,WORK12+12 end of string(p)
SR R9,R1 li=lengh(p) {r1 from edmk}
MVC EDIT12,WORK12 L12<-L13
LA R4,EDIT12+12 source+12
SR R4,R9 -lengh(p)
LR R5,R9 lengh(p)
LR R2,R10 target ix
LR R3,R9 lengh(p)
MVCL R2,R4 f=f||p
AR R10,R9 ix=ix+lengh(p)
LR R4,R7 n
SRDA R4,32 ~
DR R4,R8 /p
LR R7,R5 n=n/p
ELSE , else
LA R8,1(R8) p=p+1
ENDIF , endif
ENDDO , enddo while
ENDIF , endif
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
F DS X flag first factor
DS 0D alignment for cvd
PP DS PL8 packed CL8
EDIT12 DS CL12 target CL12
WORK12 DS CL13 char CL13
MASX12 DC X'40',9X'20',X'212060' CL13
XDEC DS CL12 temp
PG DS CL80 buffer
YREGS
END COUNTFAC</syntaxhighlight>
{{out}}
<pre style="height:20ex">
1=1
2=2
3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5
11=11
12=2*2*3
13=13
14=2*7
15=3*5
16=2*2*2*2
17=17
18=2*3*3
19=19
20=2*2*5
21=3*7
22=2*11
23=23
24=2*2*2*3
25=5*5
26=2*13
27=3*3*3
28=2*2*7
29=29
30=2*3*5
31=31
32=2*2*2*2*2
33=3*11
34=2*17
35=5*7
36=2*2*3*3
37=37
38=2*19
39=3*13
40=2*2*2*5
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintFactors(CARD a)
BYTE notFirst
CARD p
 
IF a=1 THEN
PrintC(a) RETURN
FI
 
p=2 notFirst=0
WHILE p<=a
DO
IF a MOD p=0 THEN
IF notFirst THEN
Put('x)
FI
notFirst=1
PrintC(p)
a==/p
ELSE
p==+1
FI
OD
RETURN
 
PROC Main()
CARD i
 
FOR i=1 TO 1000
DO
PrintC(i) Put('=)
PrintFactors(i)
PutE()
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Count_in_factors.png Screenshot from Atari 8-bit computer]
<pre>
1=1
2=2
3=3
4=2x2
5=5
...
995=5x199
996=2x2x3x83
997=997
998=2x499
999=3x3x3x37
1000=2x2x2x5x5x5
</pre>
 
=={{header|Ada}}==
Line 10 ⟶ 243:
 
;count.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Command_Line, Ada.Text_IO, Prime_Numbers;
procedure Count is
Line 39 ⟶ 272:
exit when N > Max_N;
end loop;
end Count;</langsyntaxhighlight>
 
{{out}}
Line 57 ⟶ 290:
14: 2 x 7
15: 3 x 5</pre>
 
=={{header|ALGOL 68}}==
{{trans|Euphoria}}<syntaxhighlight lang="algol68">
OP +:= = (REF FLEX []INT a, INT b) VOID:
BEGIN
[UPB a + 1] INT c;
c[:UPB a] := a;
c[UPB a+1:] := b;
a := c
END;
 
 
PROC factorize = (INT nn) []INT:
BEGIN
IF nn = 1 THEN (1)
ELSE
INT k := 2, n := nn;
FLEX[0]INT result;
WHILE n > 1 DO
WHILE n MOD k = 0 DO
result +:= k;
n := n % k
OD;
k +:= 1
OD;
result
FI
END;
FLEX[0]INT factors;
FOR i TO 22 DO
factors := factorize (i);
print ((whole (i, 0), " = "));
FOR j TO UPB factors DO
(j /= 1 | print (" × "));
print ((whole (factors[j], 0)))
OD;
print ((new line))
OD
</syntaxhighlight>
{{out}}
<pre>1 = 1
2 = 2
3 = 3
4 = 2 × 2
5 = 5
6 = 2 × 3
7 = 7
8 = 2 × 2 × 2
9 = 3 × 3
10 = 2 × 5
11 = 11
12 = 2 × 2 × 3
13 = 13
14 = 2 × 7
15 = 3 × 5
16 = 2 × 2 × 2 × 2
17 = 17
18 = 2 × 3 × 3
19 = 19
20 = 2 × 2 × 5
21 = 3 × 7
22 = 2 × 11</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">
begin % show numbers and their prime factors %
% shows nand its prime factors %
procedure showFactors ( integer value n ) ;
if n <= 3 then write( i_w := 1, s_w := 0, n, ": ", n )
else begin
integer v, f; logical first;
first := true;
v := n;
write( i_w := 1, s_w := 0, n, ": " );
while not odd( v ) and v > 1 do begin
if not first then writeon( s_w := 0, " x " );
writeon( i_w := 1, s_w := 0, 2 );
v := v div 2;
first := false
end while_not_odd_v ;
f := 1;
while v > 1 do begin
f := f + 2;
while v rem f = 0 do begin
if not first then writeon( s_w := 0, " x " );
writeon( i_w := 1, s_w := 0, f );
v := v div f;
first := false
end while_v_rem_f_eq_0
end while_v_gt_0_and_f_le_v
end showFactors ;
 
% show the factors of various ranges - same as Wren %
for i := 1 until 9 do showFactors( i );
write( "... " );
for i := 2144 until 2154 do showFactors( i );
write( "... " );
for i := 9987 until 9999 do showFactors( i )
end.
</syntaxhighlight>
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2 x 2
5: 5
6: 2 x 3
7: 7
8: 2 x 2 x 2
9: 3 x 3
...
2144: 2 x 2 x 2 x 2 x 2 x 67
2145: 3 x 5 x 11 x 13
2146: 2 x 29 x 37
2147: 19 x 113
2148: 2 x 2 x 3 x 179
2149: 7 x 307
2150: 2 x 5 x 5 x 43
2151: 3 x 3 x 239
2152: 2 x 2 x 2 x 269
2153: 2153
2154: 2 x 3 x 359
...
9987: 3 x 3329
9988: 2 x 2 x 11 x 227
9989: 7 x 1427
9990: 2 x 3 x 3 x 3 x 5 x 37
9991: 97 x 103
9992: 2 x 2 x 2 x 1249
9993: 3 x 3331
9994: 2 x 19 x 263
9995: 5 x 1999
9996: 2 x 2 x 3 x 7 x 7 x 17
9997: 13 x 769
9998: 2 x 4999
9999: 3 x 3 x 11 x 101
</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program countFactors.s */
 
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ NBFACT, 33
.equ MAXI, 1<<31
 
//.equ NOMBRE, 65537
//.equ NOMBRE, 99999999
.equ NOMBRE, 2144
//.equ NOMBRE, 529
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessNumber: .asciz "Number @ : "
szMessResultFact: .asciz "@ "
szCarriageReturn: .asciz "\n"
szErrorGen: .asciz "Program error !!!\n"
szMessPrime: .asciz "This number is prime.\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
tbZoneDecom: .skip 8 * NBFACT // factor 4 bytes, number of each factor 4 bytes
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r7,iNombre @ number
mov r0,r7
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrszMessNumber
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
mov r0,r7
ldr r1,iAdrtbZoneDecom
bl decompFact
cmp r0,#-1
beq 98f @ error ?
mov r1,r0
ldr r0,iAdrtbZoneDecom
bl displayDivisors
 
b 100f
98:
ldr r0,iAdrszErrorGen
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessResultFact: .int szMessResultFact
iAdrszErrorGen: .int szErrorGen
iAdrsZoneConv: .int sZoneConv
iAdrtbZoneDecom: .int tbZoneDecom
iAdrszMessNumber: .int szMessNumber
iNombre: .int NOMBRE
/******************************************************************/
/* display divisors function */
/******************************************************************/
/* r0 contains address of divisors area */
/* r1 contains the number of area items */
displayDivisors:
push {r2-r8,lr} @ save registers
cmp r1,#0
beq 100f
mov r2,r1
mov r3,#0 @ indice
mov r4,r0
1:
add r5,r4,r3,lsl #3
ldr r7,[r5] @ load factor
ldr r6,[r5,#4] @ load number of factor
mov r8,#0 @ display factor counter
2:
mov r0,r7
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrszMessResultFact
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
add r8,#1 @ increment counter
cmp r8,r6 @ same factors number ?
blt 2b
add r3,#1 @ other ithem
cmp r3,r2 @ items maxi ?
blt 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
b 100f
 
100:
pop {r2-r8,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* factor decomposition */
/******************************************************************/
/* r0 contains number */
/* r1 contains address of divisors area */
/* r0 return divisors items in table */
decompFact:
push {r1-r8,lr} @ save registers
mov r5,r1
mov r8,r0 @ save number
bl isPrime @ prime ?
cmp r0,#1
beq 98f @ yes is prime
mov r4,#0 @ raz indice
mov r1,#2 @ first divisor
mov r6,#0 @ previous divisor
mov r7,#0 @ number of same divisors
2:
mov r0,r8 @ dividende
bl division @ r1 divisor r2 quotient r3 remainder
cmp r3,#0
bne 5f @ if remainder <> zero -> no divisor
mov r8,r2 @ else quotient -> new dividende
cmp r1,r6 @ same divisor ?
beq 4f @ yes
cmp r6,#0 @ no but is the first divisor ?
beq 3f @ yes
str r6,[r5,r4,lsl #2] @ else store in the table
add r4,r4,#1 @ and increment counter
str r7,[r5,r4,lsl #2] @ store counter
add r4,r4,#1 @ next item
mov r7,#0 @ and raz counter
3:
mov r6,r1 @ new divisor
4:
add r7,r7,#1 @ increment counter
b 7f @ and loop
/* not divisor -> increment next divisor */
5:
cmp r1,#2 @ if divisor = 2 -> add 1
addeq r1,#1
addne r1,#2 @ else add 2
b 2b
/* divisor -> test if new dividende is prime */
7:
mov r3,r1 @ save divisor
cmp r8,#1 @ dividende = 1 ? -> end
beq 10f
mov r0,r8 @ new dividende is prime ?
mov r1,#0
bl isPrime @ the new dividende is prime ?
cmp r0,#1
bne 10f @ the new dividende is not prime
 
cmp r8,r6 @ else dividende is same divisor ?
beq 9f @ yes
cmp r6,#0 @ no but is the first divisor ?
beq 8f @ yes it is a first
str r6,[r5,r4,lsl #2] @ else store in table
add r4,r4,#1 @ and increment counter
str r7,[r5,r4,lsl #2] @ and store counter
add r4,r4,#1 @ next item
8:
mov r6,r8 @ new dividende -> divisor prec
mov r7,#0 @ and raz counter
9:
add r7,r7,#1 @ increment counter
b 11f
10:
mov r1,r3 @ current divisor = new divisor
cmp r1,r8 @ current divisor > new dividende ?
ble 2b @ no -> loop
/* end decomposition */
11:
str r6,[r5,r4,lsl #2] @ store last divisor
add r4,r4,#1
str r7,[r5,r4,lsl #2] @ and store last number of same divisors
add r4,r4,#1
lsr r0,r4,#1 @ return number of table items
mov r3,#0
str r3,[r5,r4,lsl #2] @ store zéro in last table item
add r4,r4,#1
str r3,[r5,r4,lsl #2] @ and zero in counter same divisor
b 100f
 
98:
ldr r0,iAdrszMessPrime
bl affichageMess
mov r0,#1 @ return code
b 100f
99:
ldr r0,iAdrszErrorGen
bl affichageMess
mov r0,#-1 @ error code
b 100f
100:
pop {r1-r8,lr} @ restaur registers
bx lr
iAdrszMessPrime: .int szMessPrime
 
/***************************************************/
/* check if a number is prime */
/***************************************************/
/* r0 contains the number */
/* r0 return 1 if prime 0 else */
@2147483647
@4294967297
@131071
isPrime:
push {r1-r6,lr} @ save registers
cmp r0,#0
beq 90f
cmp r0,#17
bhi 1f
cmp r0,#3
bls 80f @ for 1,2,3 return prime
cmp r0,#5
beq 80f @ for 5 return prime
cmp r0,#7
beq 80f @ for 7 return prime
cmp r0,#11
beq 80f @ for 11 return prime
cmp r0,#13
beq 80f @ for 13 return prime
cmp r0,#17
beq 80f @ for 17 return prime
1:
tst r0,#1 @ even ?
beq 90f @ yes -> not prime
mov r2,r0 @ save number
sub r1,r0,#1 @ exposant n - 1
mov r0,#3 @ base
bl moduloPuR32 @ compute base power n - 1 modulo n
cmp r0,#1
bne 90f @ if <> 1 -> not prime
mov r0,#5
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#7
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#11
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#13
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#17
bl moduloPuR32
cmp r0,#1
bne 90f
80:
mov r0,#1 @ is prime
b 100f
90:
mov r0,#0 @ no prime
100: @ fin standard de la fonction
pop {r1-r6,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/* */
/********************************************************/
/* r0 nombre */
/* r1 exposant */
/* r2 modulo */
/* r0 return result */
moduloPuR32:
push {r1-r7,lr} @ save registers
cmp r0,#0 @ verif <> zero
beq 100f
cmp r2,#0 @ verif <> zero
beq 100f @
1:
mov r4,r2 @ save modulo
mov r5,r1 @ save exposant
mov r6,r0 @ save base
mov r3,#1 @ start result
 
mov r1,#0 @ division de r0,r1 par r2
bl division32R
mov r6,r2 @ base <- remainder
2:
tst r5,#1 @ exposant even or odd
beq 3f
umull r0,r1,r6,r3
mov r2,r4
bl division32R
mov r3,r2 @ result <- remainder
3:
umull r0,r1,r6,r6
mov r2,r4
bl division32R
mov r6,r2 @ base <- remainder
 
lsr r5,#1 @ left shift 1 bit
cmp r5,#0 @ end ?
bne 2b
mov r0,r3
100: @ fin standard de la fonction
pop {r1-r7,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
 
/***************************************************/
/* division number 64 bits in 2 registers by number 32 bits */
/***************************************************/
/* r0 contains lower part dividende */
/* r1 contains upper part dividende */
/* r2 contains divisor */
/* r0 return lower part quotient */
/* r1 return upper part quotient */
/* r2 return remainder */
division32R:
push {r3-r9,lr} @ save registers
mov r6,#0 @ init upper upper part remainder !!
mov r7,r1 @ init upper part remainder with upper part dividende
mov r8,r0 @ init lower part remainder with lower part dividende
mov r9,#0 @ upper part quotient
mov r4,#0 @ lower part quotient
mov r5,#32 @ bits number
1: @ begin loop
lsl r6,#1 @ shift upper upper part remainder
lsls r7,#1 @ shift upper part remainder
orrcs r6,#1
lsls r8,#1 @ shift lower part remainder
orrcs r7,#1
lsls r4,#1 @ shift lower part quotient
lsl r9,#1 @ shift upper part quotient
orrcs r9,#1
@ divisor sustract upper part remainder
subs r7,r2
sbcs r6,#0 @ and substract carry
bmi 2f @ négative ?
@ positive or equal
orr r4,#1 @ 1 -> right bit quotient
b 3f
2: @ negative
orr r4,#0 @ 0 -> right bit quotient
adds r7,r2 @ and restaur remainder
adc r6,#0
3:
subs r5,#1 @ decrement bit size
bgt 1b @ end ?
mov r0,r4 @ lower part quotient
mov r1,r9 @ upper part quotient
mov r2,r7 @ remainder
100: @ function end
pop {r3-r9,lr} @ restaur registers
bx lr
 
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
Number 2144 : 2 2 2 2 2 67
</pre>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">loop 1..30 'x [
fs: [1]
if x<>1 -> fs: factors.prime x
print [pad to :string x 3 "=" join.with:" x " to [:string] fs]
]</syntaxhighlight>
 
{{out}}
 
<pre> 1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17 = 17
18 = 2 x 3 x 3
19 = 19
20 = 2 x 2 x 5
21 = 3 x 7
22 = 2 x 11
23 = 23
24 = 2 x 2 x 2 x 3
25 = 5 x 5
26 = 2 x 13
27 = 3 x 3 x 3
28 = 2 x 2 x 7
29 = 29
30 = 2 x 3 x 5</pre>
 
=={{header|AutoHotkey}}==
{{trans|D}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">factorize(n){
if n = 1
return 1
Line 76 ⟶ 877:
Loop 22
out .= A_Index ": " factorize(A_index) "`n"
MsgBox % out</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 102 ⟶ 903:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f COUNT_IN_FACTORS.AWK
BEGIN {
Line 129 ⟶ 930:
return(substr(f,1,length(f)-1))
}
</syntaxhighlight>
</lang>
<p>output:</p>
<pre>
Line 151 ⟶ 952:
6358=2*11*17*17
</pre>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="applesoftbasic"> 100 FOR I = 1 TO 20
110 GOSUB 200"FACTORIAL
120 PRINT I" = "FA$
130 NEXT I
140 END
 
200 FA$ = "1"
210 LET NUM = I
220 LET O = 5 - (I = 1) * 4
230 FOR F = 2 TO I
240 LET M = INT (NUM / F) * F
250 IF NUM - M GOTO 300
260 LET NUM = NUM / F
270 LET F$ = STR $(F)
280 FA$ = FA$ + " X " + F$
290 LET F = F - 1
 
300 NEXT F
310 FA$ = MID$ (FA$,O)
320 RETURN </syntaxhighlight>
 
==={{header|BASIC256}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="freebasic">for i = 1 to 20
print i; " = "; factorial$(i)
next i
end
 
function factorial$ (num)
factor$ = "" : x$ = ""
if num = 1 then return "1"
fct = 2
while fct <= num
if (num mod fct) = 0 then
factor$ += x$ + string(fct)
x$ = " x "
num /= fct
else
fct += 1
end if
end while
return factor$
end function</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|Run BASIC}}
<syntaxhighlight lang="qbasic">100 cls
110 for i = 1 to 20
120 rem for i = 1000 to 1016
130 print i;"= ";factorial$(i)
140 next i
150 end
160 function factorial$(num)
170 factor$ = "" : x$ = ""
180 if num = 1 then print "1"
190 fct = 2
200 while fct <= num
210 if (num mod fct) = 0 then
220 factor$ = factor$+x$+str$(fct)
230 x$ = " x "
240 num = num/fct
250 else
260 fct = fct+1
270 endif
280 wend
290 print factor$
300 end function</syntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="qbasic">FUNCTION factorial$ (num)
LET f$ = ""
LET x$ = ""
IF num = 1 THEN LET f$ = "1"
LET fct = 2
DO WHILE fct <= num
IF MOD(num, fct) = 0 THEN
LET f$ = f$ & x$ & STR$(fct)
LET x$ = " x "
LET num = num / fct
ELSE
LET fct = fct + 1
END IF
LOOP
LET factorial$ = f$
END FUNCTION
 
FOR i = 1 TO 20
PRINT i; "= "; factorial$(i)
NEXT i
END</syntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="freebasic">for i = 1 to 20
print i, " = ", factorial$(i)
next i
end
 
sub factorial$ (num)
local f$, x$
f$ = "" : x$ = ""
if num = 1 return "1"
fct = 2
while fct <= num
if mod(num, fct) = 0 then
f$ = f$ + x$ + str$(fct)
x$ = " x "
num = num / fct
else
fct = fct + 1
end if
wend
return f$
end sub</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> FOR i% = 1 TO 20
PRINT i% " = " FNfactors(i%)
NEXT
Line 170 ⟶ 1,091:
ENDWHILE
= LEFT$(f$, LEN(f$) - 3)
</syntaxhighlight>
</lang>
Output:
<pre> 1 = 1
Line 192 ⟶ 1,113:
19 = 19
20 = 2 x 2 x 5</pre>
 
=={{header|Befunge}}==
Lists the first 100 entries in the sequence. If you wish to extend that, the upper limit is implementation dependent, but may be as low as 130 for an interpreter with signed 8 bit data cells (131 is the first prime outside that range).
 
<syntaxhighlight lang="befunge">1>>>>:.48*"=",,::1-#v_.v
$<<<^_@#-"e":+1,+55$2<<<
v4_^#-1:/.:g00_00g1+>>0v
>8*"x",,:00g%!^!%g00:p0<</syntaxhighlight>
 
{{out}}
<pre>1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
.
.
.</pre>
 
=={{header|C}}==
Code includes a dynamically extending prime number list. The program doesn't stop until you kill it, or it runs out of memory, or it overflows.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 258 ⟶ 1,206:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>1 = 1
Line 277 ⟶ 1,225:
.
.</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
<lang Cpp>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
Line 288 ⟶ 1,282:
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
stringstream ss; ss << f;
res += ss.str();
li /= f; if( li == 1 ) break;
res += " x ";
Line 308 ⟶ 1,301:
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
Line 316 ⟶ 1,309:
cout << "\n\n";
return system( "pause" );
}</syntaxhighlight>
}
</lang>
{{out}}
<pre>
Line 349 ⟶ 1,341:
</pre>
 
=={{header|C sharp|C#Clojure}}==
<syntaxhighlight lang="lisp">(ns listfactors
<lang csharp>using System;
(:gen-class))
using System.Collections.Generic;
 
(defn factors
namespace prog
"Return a list of factors of N."
{
([n]
class MainClass
(factors n 2 ()))
{
([n k acc]
public static void Main (string[] args)
(cond
{
(= n 1) (if (empty? acc)
for( int i=1; i<=22; i++ )
[n]
{
(sort acc))
List<int> f = Factorize(i);
(>= k n) (if (empty? acc)
Console.Write( i + ": " + f[0] );
[n]
for( int j=1; j<f.Count; j++ )
(sort (cons n acc)))
{
(= 0 (rem n k)) (recur (quot n k) k (cons k acc))
Console.Write( " * " + f[j] );
:else (recur n (inc k) acc))))
}
 
Console.WriteLine();
(doseq [q (range 1 26)]
}
(println q " = " (clojure.string/join " x "(factors q))))
}
</syntaxhighlight>
{{Output}}
public static List<int> Factorize( int n )
<pre>
{
1 = 1
List<int> l = new List<int>();
2 = 2
if3 ( n == 1 )3
4 = 2 x 2
{
5 = 5
l.Add(1);
6 = 2 x 3
}
7 = 7
else
8 = 2 x 2 x 2
{
int9 k = 2; 3 x 3
while(10 n >= 1 )2 x 5
11 = 11
{
while(12 n %= k ==2 x 2 0x )3
13 = 13
{
14 = 2 x 7
l.Add( k );
15 = 3 x 5
n /= k;
16 = 2 x 2 x 2 x 2
}
17 = 17
k++;
18 = 2 x 3 x 3
}
19 = 19
}
20 = 2 x 2 x 5
return l;
21 = 3 x 7
}
22 = 2 x 11
}
23 = 23
}</lang>
24 = 2 x 2 x 2 x 3
25 = 5 x 5
</pre>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">count_primes = (max) ->
# Count through the natural numbers and give their prime
# factorization. This algorithm uses no division.
Line 437 ⟶ 1,432:
 
num_primes = count_primes 10000
console.log num_primes</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Auto extending prime list:
<langsyntaxhighlight lang="lisp">(defparameter *primes*
(make-array 10 :adjustable t :fill-pointer 0 :element-type 'integer))
 
Line 467 ⟶ 1,462:
 
(loop for n from 1 do
(format t "~a: ~{~a~^ × ~}~%" n (reverse (factors n))))</langsyntaxhighlight>
{{out}}
<pre>1:
Line 485 ⟶ 1,480:
...</pre>
Without saving the primes, and not all that much slower (probably because above code was not well-written):
<langsyntaxhighlight lang="lisp">(defun factors (n)
(loop with res for x from 2 to (isqrt n) do
(loop while (zerop (rem n x)) do
Line 493 ⟶ 1,488:
 
(loop for n from 1 do
(format t "~a: ~{~a~^ × ~}~%" n (reverse (factors n))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">int[] factorize(in int n) pure nothrow
in {
assert(n > 0);
Line 517 ⟶ 1,512:
foreach (i; 1 .. 22)
writefln("%d: %(%d × %)", i, i.factorize());
}</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 542 ⟶ 1,537:
===Alternative Version===
{{libheader|uiprimes}} Library ''uiprimes'' is a homebrew library to generate prime numbers upto the maximum 32bit unsigned integer range 2^32-1, by using a pre-generated bit array of [[Sieve of Eratosthenes]] (a dll in size of ~256M bytes :p ).
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.conv, std.algorithm,
std.array, std.string, import xt.uiprimes;
 
Line 573 ⟶ 1,568:
foreach (i; 1 .. 21)
writefln("%2d = %s", i, productStr(factorize(i)));
}</langsyntaxhighlight>
 
=={{header|DCL}}==
Assumes file primes.txt is a list of prime numbers;
<langsyntaxhighlight DCLlang="dcl">$ close /nolog primes
$ on control_y then $ goto clean
$
Line 619 ⟶ 1,615:
$
$ clean:
$ close /nolog primes</langsyntaxhighlight>
{{out}}
<pre>$ @count_in_factors
Line 630 ⟶ 1,626:
...
2144 = 2*2*2*2*2*67</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Count_in_factors#Pascal Pascal].
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">function Factorize(n : Integer) : String;
begin
if n <= 1 then
Line 649 ⟶ 1,647:
var i : Integer;
for i := 1 to 22 do
PrintLn(IntToStr(i) + ': ' + Factorize(i));</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 673 ⟶ 1,671:
21: 3 * 7
22: 2 * 11</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
proc decompose num . primes[] .
primes[] = [ ]
t = 2
while t * t <= num
if num mod t = 0
primes[] &= t
num = num / t
else
t += 1
.
.
primes[] &= num
.
for i = 1 to 30
write i & ": "
decompose i primes[]
for j = 1 to len primes[]
if j > 1
write " x "
.
write primes[j]
.
print ""
primes[] = [ ]
.
</syntaxhighlight>
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2 x 2
5: 5
6: 2 x 3
7: 7
8: 2 x 2 x 2
9: 3 x 3
10: 2 x 5
11: 11
12: 2 x 2 x 3
13: 13
14: 2 x 7
15: 3 x 5
16: 2 x 2 x 2 x 2
17: 17
18: 2 x 3 x 3
19: 19
20: 2 x 2 x 5
21: 3 x 7
22: 2 x 11
23: 23
24: 2 x 2 x 2 x 3
25: 5 x 5
26: 2 x 13
27: 3 x 3 x 3
28: 2 x 2 x 7
29: 29
30: 2 x 3 x 5
</pre>
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(define (task (nfrom 2) (range 20))
(for ((i (in-range nfrom (+ nfrom range))))
(writeln i "=" (string-join (prime-factors i) " x "))))
 
</syntaxhighlight>
{{out}}
<pre>
(task 1_000_000_000)
 
1000000000 = 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5
1000000001 = 7 x 11 x 13 x 19 x 52579
1000000002 = 2 x 3 x 43 x 983 x 3943
1000000003 = 23 x 307 x 141623
1000000004 = 2 x 2 x 41 x 41 x 148721
1000000005 = 3 x 5 x 66666667
1000000006 = 2 x 500000003
1000000007 = 1000000007
1000000008 = 2 x 2 x 2 x 3 x 3 x 7 x 109 x 109 x 167
1000000009 = 1000000009
1000000010 = 2 x 5 x 17 x 5882353
1000000011 = 3 x 29 x 11494253
1000000012 = 2 x 2 x 11 x 47 x 79 x 6121
1000000013 = 7699 x 129887
1000000014 = 2 x 3 x 13 x 103 x 124471
1000000015 = 5 x 7 x 31 x 223 x 4133
1000000016 = 2 x 2 x 2 x 2 x 62500001
1000000017 = 3 x 3 x 111111113
1000000018 = 2 x 500000009
1000000019 = 83 x 12048193
</pre>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 742 ⟶ 1,835:
end
 
</syntaxhighlight>
</lang>
Test Output:
 
Line 772 ⟶ 1,865:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def factor(n), do: factor(n, 2, [])
Line 783 ⟶ 1,876:
 
Enum.each(1..20, fn n ->
IO.puts "#{n}: #{Enum.join(RC.factor(n)," x ")}" end)</langsyntaxhighlight>
 
{{out}}
Line 810 ⟶ 1,903:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function factorize(integer n)
sequence result
integer k
Line 837 ⟶ 1,930:
end for
printf(1, "%d\n", factors[$])
end for</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 864 ⟶ 1,957:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
Line 874 ⟶ 1,967:
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
 
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))</langsyntaxhighlight>
{{out}}
<pre>1 = 1
Line 896 ⟶ 1,989:
2147 = 19 * 113
:
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
 
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
 
"1: 1" print 2 20 [a,b] [ .factors ] each</syntaxhighlight>
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2 × 2
5: 5
6: 2 × 3
7: 7
8: 2 × 2 × 2
9: 3 × 3
10: 2 × 5
11: 11
12: 2 × 2 × 3
13: 13
14: 2 × 7
15: 3 × 5
16: 2 × 2 × 2 × 2
17: 17
18: 2 × 3 × 3
19: 19
20: 2 × 2 × 5
</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: .factors ( n -- )
2
begin 2dup dup * >=
Line 913 ⟶ 2,039:
1+ 2 ?do i . ." : " i .factors cr loop ;
 
15 main bye</langsyntaxhighlight>
 
 
=={{header|Fortran}}==
Line 921 ⟶ 2,046:
This algorithm creates a sieve of Eratosthenes, storing the largest prime factor to mark composites. It then finds prime factors by repeatedly looking up the value in the sieve, then dividing by the factor found until the value is itself prime. Using the sieve table to store factors rather than as a plain bitmap was to me a novel idea.
 
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Thu Jun 6 23:29:06
Line 1,048 ⟶ 2,173:
call sieve(0) ! release memory
end program count_in_factors
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub getPrimeFactors(factors() As UInteger, n As UInteger)
If n < 2 Then Return
Dim factor As UInteger = 2
Do
If n Mod factor = 0 Then
Redim Preserve factors(0 To UBound(factors) + 1)
factors(UBound(factors)) = factor
n \= factor
If n = 1 Then Return
Else
factor += 1
End If
Loop
End Sub
 
Dim factors() As UInteger
 
For i As UInteger = 1 To 20
Print Using "##"; i;
Print " = ";
If i > 1 Then
Erase factors
getPrimeFactors factors(), i
For j As Integer = LBound(factors) To UBound(factors)
Print factors(j);
If j < UBound(factors) Then Print " x ";
Next j
Print
Else
Print i
End If
Next i
 
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17 = 17
18 = 2 x 3 x 3
19 = 19
20 = 2 x 2 x 5
</pre>
 
=={{header|Frink}}==
Frink's factoring routines work on arbitrarily-large integers.
<syntaxhighlight lang="frink">i = 1
while true
{
println[join[" x ", factorFlat[i]]]
i = i + 1
}</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn Factorial( num as long ) as CFStringRef
CFStringRef x, f, result
long fct
f = @"" : x = @""
if num = 1 then result = @" 1" : exit fn
fct = 2
while ( fct <= num )
if ( num mod fct == 0 )
f = fn StringWithFormat( @"%@%@%@", f, x, str( fct ) )
x = @" x"
num = num / fct
else
fct++
end if
wend
result = f
end fn = result
 
long i
for i = 1 to 20
printf @"%2ld =%@", i, fn Factorial(i)
next
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17 = 17
18 = 2 x 3 x 3
19 = 19
20 = 2 x 2 x 5
</pre>
 
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Count_in_factors}}
 
'''Solution'''
 
The '''Factor''' expression reduces to a list of the primer factors of a given number.
 
We cannot create the multiplication directly, because it would be reduced immediately to its value. We can make use of the reflection capabilities:
 
[[File:Fōrmulæ - Count in factors 01.png]]
 
[[File:Fōrmulæ - Count in factors 02.png]]
 
[[File:Fōrmulæ - Count in factors 03.png]]
 
[[File:Fōrmulæ - Count in factors 04.png]]
 
[[File:Fōrmulæ - Count in factors 05.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,069 ⟶ 2,340:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,086 ⟶ 2,357:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def factors(number) {
if (number == 1) {
return [1]
Line 1,107 ⟶ 2,378:
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}</langsyntaxhighlight>
{{out}}
<pre>1 = 1
Line 1,131 ⟶ 2,402:
=={{header|Haskell}}==
Using <code>factorize</code> function from the [[Prime_decomposition#Haskell|prime decomposition]] task,
<langsyntaxhighlight lang="haskell">import Data.List (intercalate)
 
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n</lang>
-- Pointfree form
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)</syntaxhighlight>
isPrime n = n > 1 && noDivsBy primeNums n
{{out}}
<small><langsyntaxhighlight lang="haskell">Main> print 1 >> mapM_ (putStrLn . showFactors) [2..]
1
2 = 2
Line 1,176 ⟶ 2,450:
121231231232164 = 2 * 2 * 253811 * 119410931
121231231232165 = 5 * 137 * 176979899609
. . .</langsyntaxhighlight></small>
The real solution seems to have to be some sort of a segmented offset sieve of Eratosthenes, storing factors in array's cells instead of just marks. That way the speed of production might not be diminishing as much.
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
Line 1,188 ⟶ 2,462:
end
 
link factors</langsyntaxhighlight>
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/factors.icn factors.icn provides factors]
Line 1,209 ⟶ 2,483:
16 : [ 2 2 2 2 ]
...</pre>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "Factors.bas"
110 FOR I=1 TO 30
120 PRINT I;"= ";FACTORS$(I)
130 NEXT
140 DEF FACTORS$(N)
150 LET F$=""
160 IF N=1 THEN
170 LET FACTORS$="1"
180 ELSE
190 LET P=2
200 DO WHILE P<=N
210 IF MOD(N,P)=0 THEN
220 LET F$=F$&STR$(P)&"*"
230 LET N=INT(N/P)
240 ELSE
250 LET P=P+1
260 END IF
270 LOOP
280 LET FACTORS$=F$(1:LEN(F$)-1)
290 END IF
300 END DEF</syntaxhighlight>
{{out}}
<pre> 1 = 1
2 = 2
3 = 3
4 = 2*2
5 = 5
6 = 2*3
7 = 7
8 = 2*2*2
9 = 3*3
10 = 2*5
11 = 11
12 = 2*2*3
13 = 13
14 = 2*7
15 = 3*5
16 = 2*2*2*2
17 = 17
18 = 2*3*3
19 = 19
20 = 2*2*5
21 = 3*7
22 = 2*11
23 = 23
24 = 2*2*2*3
25 = 5*5
26 = 2*13
27 = 3*3*3
28 = 2*2*7
29 = 29
30 = 2*3*5</pre>
 
=={{header|J}}==
'''Solution''':Use J's factoring primitive, <syntaxhighlight lang ="j">q:</langsyntaxhighlight>
'''Example''' (including formatting):<langsyntaxhighlight lang="j"> ('1 : 1',":&> ,"1 ': ',"1 ":@q:) 2+i.10
1 : 1
2 : 2
Line 1,223 ⟶ 2,551:
9 : 3 3
10: 2 5
11: 11</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Visual Basic .NET}}
<langsyntaxhighlight lang="java">public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
Line 1,267 ⟶ 2,595:
return n;
}
}</langsyntaxhighlight>
{{out}}
<pre>1 = 1
Line 1,291 ⟶ 2,619:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">for(i = 1; i <= 10; i++)
console.log(i + " : " + factor(i).join(" x "));
 
Line 1,305 ⟶ 2,633:
}
return factors;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,319 ⟶ 2,647:
10 : 2 x 5
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
The following uses `factors/0`, a suitable implementation of which may be found at
[[Prime_decomposition#jq]].
 
gojq supports unlimited-precision integer arithmetic, but the C implementation of jq
currently uses IEEE 754 64-bit numbers, so using the latter, the following program will only be
reliable for integers up to and including 9,007,199,254,740,992 (2^53). However, "factors"
could be easily modified to work with a "BigInt" library for jq, such as [https://gist.github.com/pkoppstein/d06a123f30c033195841 BigInt.jq].
<syntaxhighlight lang="jq"># To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
 
# Input: a non-negative integer determining when to stop
def count_in_factors:
"1: 1",
(range(2;.) | "\(.): \([factors] | join("x"))");
 
def count_in_factors($m;$n):
if . == 1 then "1: 1" else empty end,
(range($m;$n) | "\(.): \([factors] | join("x"))");
</syntaxhighlight>
'''Examples'''
<syntaxhighlight lang="jq">
10 | count_in_factors,
"",
count_in_factors(2144; 2145),
"",
(2|power(100) | count_in_factors(.; .+ 2))</syntaxhighlight>
{{out}}
The output shown here is based on a run of gojq.
<pre>
1: 1
2: 2
3: 3
4: 2x2
5: 5
6: 2x3
7: 7
8: 2x2x2
9: 3x3
 
2144: 2x2x2x2x2x67
 
1267650600228229401496703205376: 2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2x2
1267650600228229401496703205377: 17x401x61681x340801x2787601x3173389601
</pre>
 
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Primes, Printf
<lang Julia>
function factor_print{T<:Integer}strfactor(n::TInteger)
n > -2 || return "-1 × " * strfactor(-n)
const SEP = " \u00d7 "
-2 < isprime(n) || n < 2 && return "-1"*SEP*factor_printdec(-n)
iff isprime= factor(Vector{typeof(n) ||}, n < 2)
return join(f, " × return string(n")
end
a = T[]
for (k, v) in factor(n)
append!(a, k*ones(T, v))
end
sort!(a)
join(a, SEP)
end
 
lo, hi = -4, 40
println("Factor print $lo to $hi:")
hi = 40
for n in lo:hi
println("Factor print ", lo, " to ", hi)
@printf("%5d = %s\n", n, strfactor(n))
for i in lo:hi
end</syntaxhighlight>
println(@sprintf("%5d = ", i), factor_print(i))
end
</lang>
I wrote this solution's <tt>factor_print</tt> function with ease rather than efficiency in mind. It may be more efficient to first sort the keys of the <tt>factor</tt> dictionary and to build the string in place, but I find the logic of the presented solution to be clearer. The <tt>factor</tt> built-in is relevant to this solution only for integers greater than <tt>1</tt>, but I've constructed <tt>factor_print</tt> to return meaningful results for any representable proper integer.
 
{{out}}
<pre>Factor print -4 to 40:
<pre>
Factor print -4 to 40
-4 = -1 × 2 × 2
-3 = -1 × 3
Line 1,392 ⟶ 2,759:
38 = 2 × 19
39 = 3 × 13
40 = 2 × 2 × 2 × 5</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
 
fun getPrimeFactors(n: Int): List<Int> {
val factors = mutableListOf<Int>()
if (n < 1) return factors
if (n == 1 || isPrime(n)) {
factors.add(n)
return factors
}
var factor = 2
var nn = n
while (true) {
if (nn % factor == 0) {
factors.add(factor)
nn /= factor
if (nn == 1) return factors
if (isPrime(nn)) factor = nn
}
else if (factor >= 3) factor += 2
else factor = 3
}
}
 
fun main(args: Array<String>) {
val list = (MutableList(22) { it + 1 } + 2144) + 6358
for (i in list)
println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}")
}</syntaxhighlight>
 
{{out}}
<pre>
1 = 1
2 = 2
3 = 3
4 = 2 * 2
5 = 5
6 = 2 * 3
7 = 7
8 = 2 * 2 * 2
9 = 3 * 3
10 = 2 * 5
11 = 11
12 = 2 * 2 * 3
13 = 13
14 = 2 * 7
15 = 3 * 5
16 = 2 * 2 * 2 * 2
17 = 17
18 = 2 * 3 * 3
19 = 19
20 = 2 * 2 * 5
21 = 3 * 7
22 = 2 * 11
2144 = 2 * 2 * 2 * 2 * 2 * 67
6358 = 2 * 11 * 17 * 17
</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'see Run BASIC solution
for i = 1000 to 1016
Line 1,414 ⟶ 2,852:
end if
wend
end function </langsyntaxhighlight>
{{out}}
<pre>
Line 1,437 ⟶ 2,875:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function factorize( n )
if n == 1 then return {1} end
 
Line 1,460 ⟶ 2,898:
end
print ""
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Decompose function now return array (in number decomposition task return an inventory list).
 
<syntaxhighlight lang="m2000 interpreter">
Module Count_in_factors {
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
=0=1
if exist(Known1, x) then =1=1 : exit
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1
Break}
if frac(x/2) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
d += 2: if d>x1 then Append Known1, x : =1=1 : exit
if frac(x/d) else exit
d += 4: if d<= x1 else Append Known1, x : =1=1: exit
loop
}
}
decompose=lambda IsPrime (n as decimal) -> {
Factors=(,)
{
k=2@
While frac(n/k)=0
n/=k
Append Factors, (k,)
End While
if n=1 then exit
k++
While frac(n/k)=0
n/=k
Append Factors, (k,)
End While
if n=1 then exit
{
k+=2
while not isprime(k) {k+=2}
While frac(n/k)=0
n/=k : Append Factors, (k,)
End While
if n=1 then exit
loop
}
}
=Factors
}
fold=lambda (a, f$)->{
Push if$(len(f$)=0->f$, f$+"x")+str$(a,"")
}
Print "1=1"
i=1@
do
i++
Print str$(i,"")+"="+Decompose(i)#fold$(fold,"")
always
}
Count_in_factors
</syntaxhighlight>
 
=={{header|M4}}==
<syntaxhighlight lang="m4">define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl
define(`by',
`ifelse($1,$2,
$1,
`ifelse(eval($1%$2==0),1,
`$2 x by(eval($1/$2),$2)',
`by($1,eval($2+1))') ') ')dnl
define(`wby',
`$1 = ifelse($1,1,
$1,
`by($1,2)') ')dnl
 
for(`y',1,25,1, `wby(y)
')</syntaxhighlight>
 
{{out}}
<pre>
1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17 = 17
18 = 2 x 3 x 3
19 = 19
20 = 2 x 2 x 5
21 = 3 x 7
22 = 2 x 11
23 = 23
24 = 2 x 2 x 2 x 3
25 = 5 x 5
</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">factorNum := proc(n)
local i, j, firstNum;
if n = 1 then
printf("%a", 1);
end if;
firstNum := true:
for i in ifactors(n)[2] do
for j to i[2] do
if firstNum then
printf ("%a", i[1]);
firstNum := false:
else
printf(" x %a", i[1]);
end if;
end do;
end do;
printf("\n");
return NULL;
end proc:
 
for i from 1 to 10 do
printf("%2a: ", i);
factorNum(i);
end do;</syntaxhighlight>
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2 x 2
5: 5
6: 2 x 3
7: 7
8: 2 x 2 x 2
9: 3 x 3
10: 2 x 5
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,522 ⟶ 3,108:
end
return
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 30em;overflow: scroll; font-size: smaller;">
Line 1,600 ⟶ 3,186:
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">var primes = newSeq[int]()
 
proc getPrime(idx: int): int =
Line 1,620 ⟶ 3,206:
return primes[idx]
 
for x in 1 .. < int32.high.int:
stdout.write x, " = "
var n = x
var first = 1true
 
for i in 0 .. < int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first == 0: stdout.write " x "
first = 0false
stdout.write p
 
Line 1,638 ⟶ 3,224:
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""</langsyntaxhighlight>
<pre>1 = 1
2 = 2
Line 1,656 ⟶ 3,242:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class CountingInFactors {
function : Main(args : String[]) ~ Nil {
Line 1,710 ⟶ 3,296:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,736 ⟶ 3,322:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">open Big_int
 
let prime_decomposition x =
Line 1,757 ⟶ 3,343:
aux (succ_big_int v)
in
aux unit_big_int</langsyntaxhighlight>
{{out|Execution}}
<pre>$ ocamlopt -o count.opt nums.cmxa count.ml
Line 1,783 ⟶ 3,369:
=={{header|Octave}}==
Octave's factor function returns an array:
<langsyntaxhighlight lang="octave">for (n = 1:20)
printf ("%i: ", n)
printf ("%i ", factor (n))
printf ("\n")
endfor</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 1,811 ⟶ 3,397:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">fnice(n)={
fnice(n)={
my(f,s="",s1);
if (n < 2, return(n));
Line 1,817 ⟶ 3,404:
s = Str(s, f[1,1]);
if (f[1, 2] != 1, s=Str(s, "^", f[1,2]));
for(i=2,#f[,1], s1 = Str(" * ", f[i, 1]); if (f[i, 2] != 1, s1 = Str(s1, "^", f[i, 2])); s = Str(s, s1));
for(i=2,#f[,1],
s
s1 = Str(" * ", f[i, 1]);
if (f[i, 2] != 1, s1 = Str(s1, "^", f[i, 2]));
s = Str(s, s1)
);
s
};
 
n=0;while(n++, print(fnice(n)))</lang>
n=0;while(n++<21, printf("%2s: %s\n",n,fnice(n)))
</syntaxhighlight>
 
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2^2
5: 5
6: 2 * 3
7: 7
8: 2^3
9: 3^2
10: 2 * 5
11: 11
12: 2^2 * 3
13: 13
14: 2 * 7
15: 3 * 5
16: 2^4
17: 17
18: 2 * 3^2
19: 19
20: 2^2 * 5
</pre>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">program CountInFactors(output);
 
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
 
type
Line 1,834 ⟶ 3,447:
 
function factorize(number: integer): TdynArray;
var
k: integer;
begin
if number = 1 then
begin
if number =setlength(Result, 1 then);
Result[0] := 1
end
else
begin
k := 2;
while number > 1 do
begin
while number mod k = 0 do
setlength(factorize, 1);
factorize[0] := 1
end
else
begin
k := 2;
while number > 1 do
begin
setlength(Result, length(Result) + 1);
while number mod k = 0 do
Result[high(Result)] := k;
begin
number := number div k;
setlength(factorize, length(factorize) + 1);
factorize[high(factorize)] := k;
number := number div k;
end;
inc(k);
end;
end inc(k);
end;
end
end;
 
var
Line 1,872 ⟶ 3,485:
writeln;
end;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,900 ⟶ 3,513:
 
=={{header|Perl}}==
Typically one would use a module for this. Note that these modules all return an empty list for '1'. This should be efficient to 50+ digits:{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/factor/;
print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;</langsyntaxhighlight>
{{out}}
<pre>1000000000000000000 = 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5
Line 1,917 ⟶ 3,530:
 
Giving similar output and also good for large inputs:
<langsyntaxhighlight lang="perl">use Math::Pari qw/factorint/;
sub factor {
my ($pn,$pc) = @{Math::Pari::factorint(shift)};
return map { ($pn->[$_]) x $pc->[$_] } 0 .. $#$pn;
}
print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;</langsyntaxhighlight>
 
or, somewhat slower and limited to native 32-bit or 64-bit integers only:
<langsyntaxhighlight lang="perl">use Math::Factor::XS qw/prime_factors/;
print "$_ = ", join(" x ", prime_factors($_)), "\n" for 1000000000000000000 .. 1000000000000000010;</langsyntaxhighlight>
 
 
If we want to implement it self-contained, we could use the prime decomposition routine from the [[Prime_decomposition]] task. This is reasonably fast and small, though much slower than the modules and certainly could have more optimization.
<langsyntaxhighlight lang="perl">sub factors {
my($n, $p, @out) = (shift, 3);
return if $n < 1;
Line 1,945 ⟶ 3,558:
}
 
print "$_ = ", join(" x ", factors($_)), "\n" for 100000000000 .. 100000000100;</langsyntaxhighlight>
 
We could use the second extensible sieve from [[Sieve_of_Eratosthenes#Extensible_sieves]] to only divide by primes.
<langsyntaxhighlight lang="perl">tie my @primes, 'Tie::SieveOfEratosthenes';
 
sub factors {
Line 1,963 ⟶ 3,576:
}
 
print "$_ = ", join(" x ", factors($_)), "\n" for 100000000000 .. 100000000010;</langsyntaxhighlight>
{{out}}
<pre>100000000000 = 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5
Line 1,978 ⟶ 3,591:
 
This next example isn't quite as fast and uses much more memory, but it is self-contained and shows a different approach. As written it must start at 1, but a range can be handled by using a <code>map</code> to prefill the <tt>p_and_sq</tt> array.
<langsyntaxhighlight lang="perl">#!perl -C
use utf8;
use strict;
Line 2,009 ⟶ 3,622:
}
die "Ran out of primes?!";
}</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang perl6>constant @primes = grep &is-prime, 2, (3, 5, 7 ... *);
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">procedure</span> <span style="color: #000000;">factorise</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
multi factors(1) { 1 }
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prime_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
multi factors(Int $remainder is copy) {
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">),</span><span style="color: #008000;">" x "</span><span style="color: #0000FF;">)</span>
gather for @primes -> $factor {
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
# if remainder < factor², we're done
if $factor * $factor > $remainder {
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)&{</span><span style="color: #000000;">2144</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1000000000</span><span style="color: #0000FF;">},</span><span style="color: #000000;">factorise</span><span style="color: #0000FF;">)</span>
take $remainder if $remainder > 1;
<!--</syntaxhighlight>-->
last;
{{out}}
}
<pre>
 
1: 1
# How many times can we divide by this prime?
2: 2
while $remainder %% $factor {
3: 3
take $factor;
4: 2 x 2
last if ($remainder div= $factor) === 1;
5: 5
}
6: 2 }x 3
7: 7
}
8: 2 x 2 x 2
 
9: 3 x 3
say "$_: ", factors($_).join(" × ") for 1..*;</lang>
10: 2 x 5
The first twenty numbers:
2144: 2 x 2 x 2 x 2 x 2 x 67
<pre>1: 1
1000000000: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5
2: 2
</pre>
3: 3
4: 2 × 2
5: 5
6: 2 × 3
7: 7
8: 2 × 2 × 2
9: 3 × 3
10: 2 × 5
11: 11
12: 2 × 2 × 3
13: 13
14: 2 × 7
15: 3 × 5
16: 2 × 2 × 2 × 2
17: 17
18: 2 × 3 × 3
19: 19
20: 2 × 2 × 5</pre>
Here we use a <tt>multi</tt> declaration with a constant parameter to match the degenerate case. We use <tt>copy</tt> parameters when we wish to reuse the formal parameter as a mutable variable within the function. (Parameters default to readonly in Perl&nbsp;6.) Note the use of <tt>gather</tt>/<tt>take</tt> as the final statement in the function, which is a common Perl&nbsp;6 idiom to set up a coroutine within a function to return a lazy list on demand.
 
Note also the '×' above is not ASCII 'x', but U+00D7 MULTIPLICATION SIGN. Perl&nbsp;6 does Unicode natively.
 
Here is a solution inspired from [[Almost_prime#C]]. It doesn't use &is-prime.
 
<lang perl6>sub factor($n is copy) {
$n == 1 ?? 1 !!
gather {
$n /= take 2 while $n %% 2;
$n /= take 3 while $n %% 3;
loop (my $p = 5; $p*$p <= $n; $p+=2) {
$n /= take $p while $n %% $p;
}
take $n unless $n == 1;
}
}
 
say "$_ == ", join " \x00d7 ", factor $_ for 1 .. 20;
</lang>
 
=={{header|PicoLisp}}==
This is the 'factor' function from [[Prime decomposition#PicoLisp]].
<langsyntaxhighlight PicoLisplang="picolisp">(de factor (N)
(make
(let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N))
Line 2,087 ⟶ 3,663:
 
(for N 20
(prinl N ": " (glue " * " (factor N))) )</langsyntaxhighlight>
{{out}}
<pre>1: 1
Line 2,111 ⟶ 3,687:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
cnt: procedure options (main);
declare (i, k, n) fixed binary;
Line 2,136 ⟶ 3,712:
end;
end cnt;
</syntaxhighlight>
</lang>
Results:
<pre> 1 = 1
Line 2,181 ⟶ 3,757:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function eratosthenes ($n) {
if($n -ge 1){
Line 2,214 ⟶ 3,790:
"$(prime-decomposition 100)"
"$(prime-decomposition 12)"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,223 ⟶ 3,799:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Factorize(Number, List Factors())
Protected I = 3, Max
ClearList(Factors())
Line 2,260 ⟶ 3,836:
PrintN(text$)
Next a
EndIf</langsyntaxhighlight>
{{out}}
<pre> 1= 1
Line 2,285 ⟶ 3,861:
=={{header|Python}}==
This uses the [http://docs.python.org/dev/library/functools.html#functools.lru_cache functools.lru_cache] standard library module to cache intermediate results.
<langsyntaxhighlight lang="python">from functools import lru_cache
 
primes = [2, 3, 5, 7, 11, 13, 17] # Will be extended
Line 2,319 ⟶ 3,895:
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())</langsyntaxhighlight>
{{out}}
<pre> 1 1
Line 2,357 ⟶ 3,933:
CacheInfo(hits=3935, misses=7930, maxsize=2000, currsize=2000)</pre>
 
=={{header|Racket}}==
<lang racket>
#lang racket
(require math)
 
=={{header|Quackery}}==
(define (~ f)
(match f
[(list p 1) (~a p)]
[(list p n) (~a p "^" n)]))
 
Reusing the code from [http://rosettacode.org/wiki/Prime_decomposition#Quackery Prime Decomposition].
(for ([x (in-range 2 20)])
 
(display (~a x " = "))
<syntaxhighlight lang="quackery"> [ [] swap
(for-each display (add-between (map ~ (factorize x)) " * "))
dup times
(newline))
[ [ dup i^ 2 + /mod
</lang>
0 = while
Output:
nip dip
[ i^ 2 + join ]
again ]
drop
dup 1 = if conclude ]
drop ] is primefactors ( n --> [ )
[ 1 dup echo cr
[ 1+ dup primefactors
witheach
[ echo
i if [ say " x " ] ]
cr again ] ] is countinfactors ( --> )
 
countinfactors</syntaxhighlight>
 
{{out}}
 
<pre>1
2
3
2 x 2
5
2 x 3
7
2 x 2 x 2
3 x 3
2 x 5
11
2 x 2 x 3
13
2 x 7
3 x 5
2 x 2 x 2 x 2
17
2 x 3 x 3
19
2 x 2 x 5
3 x 7
2 x 11
23</pre>
… and so on. Quackery uses bignums, so "… until boredom ensues."
 
=={{header|R}}==
<syntaxhighlight lang="r">
#initially I created a function which returns prime factors then I have created another function counts in the factors and #prints the values.
 
findfactors <- function(num) {
x <- c()
p1<- 2
p2 <- 3
everyprime <- num
while( everyprime != 1 ) {
while( everyprime%%p1 == 0 ) {
x <- c(x, p1)
everyprime <- floor(everyprime/ p1)
}
p1 <- p2
p2 <- p2 + 2
}
x
}
count_in_factors=function(x){
primes=findfactors(x)
x=c(1)
for (i in 1:length(primes)) {
x=paste(primes[i],"x",x)
}
return(x)
}
count_in_factors(72)
</syntaxhighlight>
 
{{out}}
<pre>
[1] "3 x 3 x 2 x 2 x 2 x 1"
</pre>
 
=={{header|Racket}}==
See also [[#Scheme]]. This uses Racket&rsquo;s <code>math/number-theory</code> package
 
<syntaxhighlight lang="racket">#lang typed/racket
 
(require math/number-theory)
 
(define (factorise-as-primes [n : Natural])
(if
(= n 1)
'(1)
(let ((F (factorize n)))
(append*
(for/list : (Listof (Listof Natural))
((f (in-list F)))
(make-list (second f) (first f)))))))
 
(define (factor-count [start-inc : Natural] [end-inc : Natural])
(for ((i : Natural (in-range start-inc (add1 end-inc))))
(define f (string-join (map number->string (factorise-as-primes i)) " × "))
(printf "~a:\t~a~%" i f)))
 
(factor-count 1 22)
(factor-count 2140 2150)
; tb</syntaxhighlight>
 
{{out}}
 
<pre>1: 1
2: 2
3: 3
4: 2 × 2
5: 5
6: 2 × 3
7: 7
8: 2 × 2 × 2
9: 3 × 3
10: 2 × 5
11: 11
12: 2 × 2 × 3
13: 13
14: 2 × 7
15: 3 × 5
16: 2 × 2 × 2 × 2
17: 17
18: 2 × 3 × 3
19: 19
20: 2 × 2 × 5
21: 3 × 7
22: 2 × 11
2140: 2 × 2 × 5 × 107
2141: 2141
2142: 2 × 3 × 3 × 7 × 17
2143: 2143
2144: 2 × 2 × 2 × 2 × 2 × 67
2145: 3 × 5 × 11 × 13
2146: 2 × 29 × 37
2147: 19 × 113
2148: 2 × 2 × 3 × 179
2149: 7 × 307
2150: 2 × 5 × 5 × 43</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-10-01}}
<syntaxhighlight lang="raku" line>constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;
 
multi factors(1) { 1 }
multi factors(Int $remainder is copy) {
gather for @primes -> $factor {
 
# if remainder < factor², we're done
if $factor * $factor > $remainder {
take $remainder if $remainder > 1;
last;
}
 
# How many times can we divide by this prime?
while $remainder %% $factor {
take $factor;
last if ($remainder div= $factor) === 1;
}
}
}
 
say "$_: ", factors($_).join(" × ") for 1..*;</syntaxhighlight>
The first twenty numbers:
<pre>1: 1
2: 2
3: 3
4: 2 × 2
5: 5
6: 2 × 3
7: 7
8: 2 × 2 × 2
9: 3 × 3
10: 2 × 5
11: 11
12: 2 × 2 × 3
13: 13
14: 2 × 7
15: 3 × 5
16: 2 × 2 × 2 × 2
17: 17
18: 2 × 3 × 3
19: 19
20: 2 × 2 × 5</pre>
Here we use a <tt>multi</tt> declaration with a constant parameter to match the degenerate case. We use <tt>copy</tt> parameters when we wish to reuse the formal parameter as a mutable variable within the function. (Parameters default to readonly in Raku.) Note the use of <tt>gather</tt>/<tt>take</tt> as the final statement in the function, which is a common Raku idiom to set up a coroutine within a function to return a lazy list on demand.
 
Note also the '×' above is not ASCII 'x', but U+00D7 MULTIPLICATION SIGN. Raku does Unicode natively.
 
Here is a solution inspired from [[Almost_prime#C]]. It doesn't use &is-prime.
 
<syntaxhighlight lang="raku" line>sub factor($n is copy) {
$n == 1 ?? 1 !!
gather {
$n /= take 2 while $n %% 2;
$n /= take 3 while $n %% 3;
loop (my $p = 5; $p*$p <= $n; $p+=2) {
$n /= take $p while $n %% $p;
}
take $n unless $n == 1;
}
}
 
say "$_ == ", join " \x00d7 ", factor $_ for 1 .. 20;</syntaxhighlight>
 
Same output as above.
 
 
Alternately, use a module:
 
<syntaxhighlight lang="raku" line>use Prime::Factor;
 
say "$_ = {(.&prime-factors || 1).join: ' x ' }" for flat 1 .. 10, 10**20 .. 10**20 + 10;</syntaxhighlight>
{{out}}
<pre>1 = 1
2 = 2
3 = 3
4 = 2^ x 2
5 = 5
6 = 2 *x 3
7 = 7
8 = 2^3 x 2 x 2
9 = 3^2 x 3
10 = 2 *x 5
100000000000000000000 = 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5
11 = 11
100000000000000000001 = 73 x 137 x 1676321 x 5964848081
12 = 2^2 * 3
100000000000000000002 = 2 x 3 x 155977777 x 106852828571
13 = 13
100000000000000000003 = 373 x 155773 x 1721071782307
14 = 2 * 7
100000000000000000004 = 2 x 2 x 13 x 1597 x 240841 x 4999900001
15 = 3 * 5
100000000000000000005 = 3 x 5 x 7 x 7 x 83 x 1663 x 985694468327
16 = 2^4
100000000000000000006 = 2 x 31 x 6079 x 265323774602147
17 = 17
100000000000000000007 = 67 x 166909 x 8942221889969
18 = 2 * 3^2
100000000000000000008 = 2 x 2 x 2 x 3 x 3 x 3 x 233 x 1986965506278811
19 = 19
100000000000000000009 = 557 x 72937 x 2461483384901
</pre>
100000000000000000010 = 2 x 5 x 11 x 909090909090909091</pre>
 
=={{header|REXXRefal}}==
<syntaxhighlight language="refal">$ENTRY Go {
It couldn't be determined if the showing of the &nbsp; '''x''' &nbsp; (for multiplication) was a strict requirement or whether
= <Each Show <Iota 1 15> 2144>;
<br>there are (or can be) &nbsp; blanks surrounding the &nbsp; '''x''' &nbsp; (blanks were assumed for this example for readability).
};
 
Factorize {
There's commented code that shows how to not include blanks around the &nbsp; '''x''' &nbsp;
1 = 1;
<br> &nbsp; &nbsp; [see comments about &nbsp; '''blanks=1''' &nbsp; &nbsp; (8<sup>th</sup> statement)].
s.N = <Factorize 2 s.N>;
s.D s.N, <Compare s.N s.D>: '-' = ;
s.D s.N, <Divmod s.N s.D>: {
(s.R) 0 = s.D <Factorize s.D s.R>;
e.X = <Factorize <+ 1 s.D> s.N>;
};
};
 
Join {
'''blanks=0''' &nbsp; will remove all blanks around the &nbsp; '''x'''.
(e.J) = ;
(e.J) s.N = <Symb s.N>;
(e.J) s.N e.X = <Symb s.N> e.J <Join (e.J) e.X>;
};
 
Iota {
s.End s.End = s.End;
s.Start s.End = s.Start <Iota <+ s.Start 1> s.End>;
};
 
Each {
Also, as per the task's requirements, the prime factors of &nbsp; '''1''' &nbsp; (unity) will be listed as &nbsp; '''1''',
s.F = ;
s.F t.I e.X = <Mu s.F t.I> <Each s.F e.X>;
};
 
Show {
e.N = <Prout <Symb e.N> ' = ' <Join (' x ') <Factorize e.N>>>;
}; </syntaxhighlight>
{{out}}
<pre>1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
2144 = 2 x 2 x 2 x 2 x 2 x 67</pre>
 
=={{header|REXX}}==
===simple approach===
As per the task's requirements, the prime factors of &nbsp; '''1''' &nbsp; (unity) will be listed as &nbsp; '''1''',
<br>even though, strictly speaking, it should be &nbsp; '''null'''. &nbsp; &nbsp; &nbsp; &nbsp; The same applies to &nbsp; '''0'''.
 
Programming note: &nbsp; if the HIGH&nbsp; '''high''' &nbsp; argument is negative, its positive value is used and no displaying of the
<br>prime factors are listed, but the number of primes found is always shown. &nbsp; The showing of the count of
<br>primes was included to help verify the factoring (of composites).
<langsyntaxhighlight lang="rexx">/*REXX program lists the prime factors of a specified integer (or a range of integers).*/
@.=left('', 8); @.0='"{unity} '"; @.1='[prime] '; X='x' /*some tags and handy-dandy literals.*/
parse arg lowLO highHI @ . /*get optional arguments from the C.L. */
if lowLO=='' | LO=="," then do;low LO=1;high HI=40; end /*No LOW &Not HIGHspecified? Then use the default.*/
if highHI=='' | HI=="," then highHI=low; oHigh=highLO /*No HIGH?" " " " " " */
if @=='' then @= 'x' /* " " " " " " */
w=length(high); high=abs(high) /*get maximum width for pretty output. */
numericif digits maxlength(9,w+@)\==1 then @= x2c(@) /*maybeNot bumplength 1? the precisionThen ofuse numbershexadecimal. */
blankstell=1 (HI>0) /*1:if HIGH allowsis spacespositive, aroundthen theshow "x"#'s. */
#HI=0 abs(HI) /*use the numberabsolute ofvalue primesfor found (so far)HIGH. */
w= length(HI) /*get maximum width for pretty output. */
do n=low to high; f=factr(n) /*process a single number or a range.*/
numeric digits max(9, w + p=words(translate(f,,X))-(n==1) /*P:maybe isbump the numberprecision of prime factorsnumbers. */
#= 0 if p==1 then #=#+1 /*bump the number of primes counterfound (excludeso N=1far). */
ifdo high\n==oHighabs(LO) thento iterateHI; /*only show factors if f= HIGHfactr(n) is >/*process 0.a single number or a range.*/
sayp= rightwords(n translate(f,w ,@) '=') - @.p space(f,blanksn==1) /*showP: is the primenumber flagof andprime factors. */
endif p==1 /*n*/then #= # + 1 /*if BLANKS=0, then/*bump nothe spacesprimes aroundcounter X(exclude N=1)*/
if tell then say right(n, w) '=' @.p f /*display if a prime, plus its factors.*/
end /*n*/
say
say right(#, w) ' primes found.' /*display the number of primes found. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
factr: procedure expose X@; parse arg qz 1 zn,$; if qz<2 then return qz /*0│1is Z too small?*/
j=2; if do while z//j2==0; then call$= .add$||@||2; z= z%2; /* [↓] processend /*maybe add afactor specificof prime (2). */
j=3; if do while z//j3==0; then call$= .add$||@||3; z= z%3; end /* [↓] " " " process a specific" prime (3). */
j=5; if do while z//j5==0; then call$= .add$||@||5; z= z%5; end /* [↓] " " " process a specific" prime (5). */
do y while z//7==0; by 2$= $||@||7; jz=j+2+y//4 z%7; end /*insure it's not" " " divisible" by three. 7 */
parse var j '' -1 _ /*obtain the last decimal digit of J. */
if _==5 then iterate /*fast check for divisible by five. */
if j>z then leave /*number reduced enough? ___ */
if j*j>q then leave /*are we higher than the √ Q ? */
if z//j==0 then call .add$ /*add a prime factor (J) to the $ list.*/
end /*y*/
 
if z==1 then z= do j=11 by 6 while j<=z /*ifinsure that residualJ is unity,isn't thendivisible nullifyby it3.*/
parse var j '' -1 _ /*get the last decimal digit of J. */
return strip(strip($ X z),,X) /*elide a possible leading (extra) "x".*/
if _\==5 then do while z//j==0; $=$||@||j; z= z%j; end /*maybe reduce Z.*/
/*────────────────────────────────────────────────────────────────────────────*/
if _ ==3 then iterate /*Next # ÷ by 5? Skip. ___ */
.add$: do while z//j==0; $=$ X j; z=z%j; end; return /*add J─►$; integer ÷*/</lang>
if j*j>n then leave /*are we higher than the √ N ? */
'''output''' when using the defaults for input:
y= j + 2 /*obtain the next odd divisor. */
<pre style="height:40ex">
do while z//y==0; $=$||@||y; z= z%y; end /*maybe reduce Z.*/
end /*j*/
if z==1 then return substr($, 1+length(@) ) /*Is residual=1? Don't add 1*/
return substr($||@||z, 1+length(@) ) /*elide superfluous header. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
1 = {unity} 1
2 = [prime] 2
3 = [prime] 3
4 = 2x2
5 = [prime] 5
6 = 2x3
7 = [prime] 7
8 = 2x2x2
9 = 3x3
10 = 2x5
11 = [prime] 11
12 = 2x2x3
13 = [prime] 13
14 = 2x7
15 = 3x5
16 = 2x2x2x2
17 = [prime] 17
18 = 2x3x3
19 = [prime] 19
20 = 2x2x5
21 = 3x7
22 = 2x11
23 = [prime] 23
24 = 2x2x2x3
25 = 5x5
26 = 2x13
27 = 3x3x3
28 = 2x2x7
29 = [prime] 29
30 = 2x3x5
31 = [prime] 31
32 = 2x2x2x2x2
33 = 3x11
34 = 2x17
35 = 5x7
36 = 2x2x3x3
37 = [prime] 37
38 = 2x19
39 = 3x13
40 = 2x2x2x5
 
12 primes found.
</pre>
{{out|output|text=&nbsp; when the following input was used: &nbsp; &nbsp; <tt> 1 &nbsp; 12 &nbsp; 207820 </tt>}}
<pre>
1 = {unity} 1
2 = [prime] 2
Line 2,459 ⟶ 4,334:
11 = [prime] 11
12 = 2 x 2 x 3
 
5 primes found.
</pre>
{{out|output|text=&nbsp; when the following input was used: &nbsp; &nbsp; <tt> 1 &nbsp; -10000 </tt>}}
<pre>
1229 primes found.
</pre>
{{out|output|text=&nbsp; when the following input was used: &nbsp; &nbsp; <tt> 1 &nbsp; -100000 </tt>}}
<pre>
9592 primes found.
</pre>
 
===using integer SQRT===
This REXX version computes the &nbsp; ''integer square root'' &nbsp; of the integer being factor &nbsp; (to limit the range of factors),
<br>this makes this version about &nbsp; '''50%''' &nbsp; faster than the 1<sup>st</sup> REXX version.
 
Also, the number of early testing of prime factors was expanded.
 
Note that the &nbsp; '''integer square root''' &nbsp; section of code doesn't use any floating point numbers, just integers.
<syntaxhighlight lang="rexx">/*REXX program lists the prime factors of a specified integer (or a range of integers).*/
@.=left('', 8); @.0="{unity} "; @.1='[prime] ' /*some tags and handy-dandy literals.*/
parse arg LO HI @ . /*get optional arguments from the C.L. */
if LO=='' | LO=="," then do; LO=1; HI=40; end /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= LO /* " " " " " " */
if @=='' then @= 'x' /* " " " " " " */
if length(@)\==1 then @= x2c(@) /*Not length 1? Then use hexadecimal. */
tell= (HI>0) /*if HIGH is positive, then show #'s.*/
HI= abs(HI) /*use the absolute value for HIGH. */
w= length(HI) /*get maximum width for pretty output. */
numeric digits max(9, w + 1) /*maybe bump the precision of numbers. */
#= 0 /*the number of primes found (so far). */
do n=abs(LO) to HI; f= factr(n) /*process a single number or a range.*/
p= words( translate(f, ,@) ) - (n==1) /*P: is the number of prime factors. */
if p==1 then #= # + 1 /*bump the primes counter (exclude N=1)*/
if tell then say right(n, w) '=' @.p f /*display if a prime, plus its factors.*/
end /*n*/
say
say right(#, w) ' primes found.' /*display the number of primes found. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: procedure expose @; parse arg z 1 n,$; if z<2 then return z /*is Z too small?*/
do while z// 2==0; $= $||@||2 ; z= z%2 ; end /*maybe add factor of 2 */
do while z// 3==0; $= $||@||3 ; z= z%3 ; end /* " " " " 3 */
do while z// 5==0; $= $||@||5 ; z= z%5 ; end /* " " " " 5 */
do while z// 7==0; $= $||@||7 ; z= z%7 ; end /* " " " " 7 */
do while z//11==0; $= $||@||11; z= z%11; end /* " " " " 11 */
do while z//13==0; $= $||@||13; z= z%13; end /* " " " " 13 */
do while z//17==0; $= $||@||17; z= z%17; end /* " " " " 17 */
do while z//19==0; $= $||@||19; z= z%19; end /* " " " " 19 */
do while z//23==0; $= $||@||23; z= z%23; end /* " " " " 23 */
do while z//29==0; $= $||@||29; z= z%29; end /* " " " " 29 */
do while z//31==0; $= $||@||31; z= z%31; end /* " " " " 31 */
do while z//37==0; $= $||@||37; z= z%37; end /* " " " " 37 */
if z>40 then do; t= z; q= 1; r= 0; do while q<=t; q= q * 4
end /*while*/
do while q>1; q=q%4; _=t-r-q; r=r%2; if _>=0 then do; t=_; r=r+q
end
end /*while*/ /* [↑] find integer SQRT(z). */
/*R: is the integer SQRT of Z.*/
do j=41 by 6 to r while j<=z /*insure J isn't divisible by 3*/
parse var j '' -1 _ /*get last decimal digit of J.*/
if _\==5 then do while z//j==0; $=$||@||j; z= z%j; end
if _ ==3 then iterate /*Next number ÷ by 5 ? Skip.*/
y= j + 2 /*use the next (odd) divisor. */
do while z//y==0; $=$||@||y; z= z%y; end
end /*j*/ /* [↑] reduce Z by Y ? */
end /*if z>40*/
 
if z==1 then return substr($, 1+length(@) ) /*Is residual=1? Don't add 1*/
return substr($||@||z, 1+length(@) ) /*elide superfluous header. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
1 = {unity} 1
2 = [prime] 2
3 = [prime] 3
4 = 2∙2
5 = [prime] 5
6 = 2∙3
7 = [prime] 7
8 = 2∙2∙2
9 = 3∙3
10 = 2∙5
11 = [prime] 11
12 = 2∙2∙3
13 = [prime] 13
14 = 2 x 72∙7
15 = 3 x 53∙5
16 = 2 x 2 x 2 x 22∙2∙2∙2
17 = [prime] 17
18 = 2 x 3 x 32∙3∙3
19 = [prime] 19
20 = 2 x 2 x 52∙2∙5
21 = 3 x 73∙7
22 = 2 x 112∙11
23 = [prime] 23
24 = 2 x 2 x 2 x 32∙2∙2∙3
25 = 5 x 55∙5
26 = 2 x 132∙13
27 = 3 x 3 x 33∙3∙3
28 = 2 x 2 x 72∙2∙7
29 = [prime] 29
30 = 2 x 3 x 52∙3∙5
31 = [prime] 31
32 = 2 x 2 x 2 x 2 x 22∙2∙2∙2∙2
33 = 3 x 113∙11
34 = 2 x 172∙17
35 = 5 x 75∙7
36 = 2 x 2 x 3 x 32∙2∙3∙3
37 = [prime] 37
38 = 2 x 192∙19
39 = 3 x 133∙13
40 = 2 x 2 x 2 x 52∙2∙2∙5
 
12 primes found.
</pre>
 
'''output''' when the following input was used: &nbsp; <tt> 1 &nbsp; -10000 </tt>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
for i = 1 to 20
see "" + i + " = " + factors(i) + nl
next
func factors n
f = ""
if n = 1 return "1" ok
p = 2
while p <= n
if (n % p) = 0
f += string(p) + " x "
n = n/p
else p += 1 ok
end
return left(f, len(f) - 3)
</syntaxhighlight>
Output:
<pre>
1 = 1
1229 primes found.
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17 = 17
18 = 2 x 3 x 3
19 = 19
20 = 2 x 2 x 5
</pre>
 
=={{header|RPL}}==
<code>PDIV</code> is defined at [[Prime decomposition#RPL|Prime decomposition]]
≪ { "1" } 2 ROT '''FOR''' j
"" j <span style="color:blue">PDIV</span> → factors
≪ '''IF''' factors SIZE 1 == '''THEN''' j →STR +
'''ELSE'''
1 factors SIZE '''FOR''' k
'''IF''' k 1 ≠ '''THEN''' 130 CHR + '''END'''
factors k GET →STR +
'''NEXT END'''
≫ + '''NEXT'''
≫ '<span style="color:blue">TASK</span>' STO
 
20 <span style="color:blue">TASK</span>
{{out}}
<pre>
1: { "1" "2" "3" "2×2" "5" "2×3" "7" "2×2×2" "3×3" "2×5" "11" "2×2×3" "13" "2×7" "3×5" "2×2×2×2" "17" "2×3×3" "19" "2×2×5" }
</pre>
 
=={{header|Ruby}}==
Starting with Ruby 1.9, 'prime' is part of the standard library and provides Integer#prime_division.
<langsyntaxhighlight lang="ruby">require 'optparse'
require 'prime'
 
Line 2,519 ⟶ 4,535:
end.join " x "
puts "#{i} is #{f}"
end</langsyntaxhighlight>
{{out|Example}}
<pre>$ ruby prime-count.rb -h
Line 2,547 ⟶ 4,563:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for i = 1000 to 1016
print i;" = "; factorial$(i)
next
Line 2,563 ⟶ 4,579:
end if
wend
end function</langsyntaxhighlight>
{{out}}
<pre>1000 = 2 x 2 x 2 x 5 x 5 x 5
Line 2,582 ⟶ 4,598:
1015 = 5 x 7 x 29
1016 = 2 x 2 x 2 x 127</pre>
 
=={{header|Rust}}==
You can run and experiment with this code at https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b66c14d944ff0472d2460796513929e2
<syntaxhighlight lang="rust">use std::env;
 
fn main() {
let args: Vec<_> = env::args().collect();
let n = if args.len() > 1 {
args[1].parse().expect("Not a valid number to count to")
}
else {
20
};
count_in_factors_to(n);
}
 
fn count_in_factors_to(n: u64) {
println!("1");
let mut primes = vec![];
for i in 2..=n {
let fs = factors(&primes, i);
if fs.len() <= 1 {
primes.push(i);
println!("{}", i);
}
else {
println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x "));
}
}
}
 
fn factors(primes: &[u64], mut n: u64) -> Vec<u64> {
let mut result = Vec::new();
for p in primes {
while n % p == 0 {
result.push(*p);
n /= p;
}
if n == 1 {
return result;
}
}
vec![n]
}</syntaxhighlight>
{{out}}
<pre>1
2
3
4 = 2 x 2
5
6 = 2 x 3
7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11
12 = 2 x 2 x 3
13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17
18 = 2 x 3 x 3
19
20 = 2 x 2 x 5
</pre>
 
=={{header|Sage}}==
<syntaxhighlight lang="python">def count_in_factors(n):
if is_prime(n) or n == 1:
print(n,end="")
return
while n != 1:
p = next_prime(1)
while n % p != 0:
p = next_prime(p)
print(p,end="")
n = n / p
if n != 1: print(" x",end=" ")
 
for i in range(1, 101):
print(i,"=",end=" ")
count_in_factors(i)
print("")</syntaxhighlight>
 
{{out}}
<pre>
1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17 = 17
18 = 2 x 3 x 3
19 = 19
20 = 2 x 2 x 5
21 = 3 x 7
22 = 2 x 11
23 = 23
24 = 2 x 2 x 2 x 3
25 = 5 x 5
26 = 2 x 13
27 = 3 x 3 x 3
28 = 2 x 2 x 7
29 = 29
30 = 2 x 3 x 5
31 = 31
32 = 2 x 2 x 2 x 2 x 2
33 = 3 x 11
34 = 2 x 17
35 = 5 x 7
36 = 2 x 2 x 3 x 3
37 = 37
38 = 2 x 19
39 = 3 x 13
40 = 2 x 2 x 2 x 5
41 = 41
...
85 = 5 x 17
86 = 2 x 43
87 = 3 x 29
88 = 2 x 2 x 2 x 11
89 = 89
90 = 2 x 3 x 3 x 5
91 = 7 x 13
92 = 2 x 2 x 23
93 = 3 x 31
94 = 2 x 47
95 = 5 x 19
96 = 2 x 2 x 2 x 2 x 2 x 3
97 = 97
98 = 2 x 7 x 7
99 = 3 x 3 x 11
100 = 2 x 2 x 5 x 5</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">
<lang scala>def primeFactors( n:Int ) = {
object CountInFactors extends App {
 
def primeStreamprimeFactors(sn: Stream[Int]): StreamList[Int] = {
s.head #:: primeStream(s.tail filter { _ % s.head != 0 })
}
 
val primes =def primeStream(Stream.from(2)s: LazyList[Int]): LazyList[Int] = {
s.head #:: primeStream(s.tail filter {
_ % s.head != 0
})
}
 
val primes = primeStream(LazyList.from(2))
def factors( n:Int ) : List[Int] = primes.takeWhile( _ <= n ).find( n % _ == 0 ) match {
 
case None => Nil
def factors(n: Int): List[Int] = primes.takeWhile(_ <= n).find(n % _ == 0) match {
case Some(p) => p :: factors( n/p )
case None => Nil
case Some(p) => p :: factors(n / p)
}
 
if (n == 1) List(1) else factors(n)
}
 
// A little test...
{
val nums = (1 to 12).toList :+ 2144 :+ 6358
nums.foreach(n => println("%6d : %s".format(n, primeFactors(n).mkString(" * "))))
}
if( n == 1 ) List(1) else factors(n)
}
 
// A little test...
{
val nums = (1 to 12).toList :+ 2144 :+ 6358
nums.foreach( n => println( "%6d : %s".format( n, primeFactors(n).mkString(" * ") ) ) )
}
</syntaxhighlight>
</lang>
{{out}}
<pre> 1 : 1
Line 2,623 ⟶ 4,791:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="lisp">(define (factors n)
(let facs ((l '()) (d 2) (x n))
(cond ((= x 1) (if (null? l) '(1) l))
Line 2,642 ⟶ 4,810:
(display i)
(display " = ")
(show (reverse (factors i))))</langsyntaxhighlight>
{{out}}
<pre>1 = 1
Line 2,659 ⟶ 4,827:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: writePrimeFactors (in var integer: number) is func
Line 2,697 ⟶ 4,865:
writeln;
end for;
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,719 ⟶ 4,887:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Counter {
method factors(n, p=2) {
var outa = [];gather {
while (n >= p*p) {
while (np %%`divides` pn) {
out.append take(p);
n //= p;
};
p = self.next_prime(p);
};
}
(n > 1 || out.len.isZero) && out.append(n);
(n > 1 || a.is_empty) ? (a << n) : a
return out;
}
 
 
method is_prime(n) {
self.factors(n).len == 1
}
 
 
method next_prime(p) {
do { p == 2 ? (p = 3) : (p+=2) }
dop == while2 ? (p = 3) : {!self.is_prime(p+=2)};
return} while (!self.is_prime(p;))
return p
}
}
 
for i in (1..100) {
say "#{i} = #{Counter().factors(i).join(' × ')}"
}</syntaxhighlight>
 
=={{header|Swift}}==
{ |i|
 
say "#{i} = #{Counter().factors(i).join(' × ')}";
<syntaxhighlight lang="swift">extension BinaryInteger {
} * 100;</lang>
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
 
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
 
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
var q: Self = self & 1 == 0 ? 2 : 3
 
while q <= maxQ && self % q != 0 {
q = step(d)
d += 1
}
 
return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self]
}
}
 
for i in 1...20 {
if i == 1 {
print("1 = 1")
} else {
print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " x "))")
}
}</syntaxhighlight>
 
{{out}}
 
<pre>1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
11 = 11
12 = 2 x 2 x 3
13 = 13
14 = 2 x 7
15 = 3 x 5
16 = 2 x 2 x 2 x 2
17 = 17
18 = 2 x 3 x 3
19 = 19
20 = 2 x 2 x 5</pre>
 
=={{header|Tcl}}==
This factorization code is based on the same engine that is used in the [[Parallel calculations#Tcl|parallel computation task]].
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
namespace eval prime {
Line 2,811 ⟶ 5,035:
return [join $v "*"]
}
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl">set max 20
for {set i 1} {$i <= $max} {incr i} {
puts [format "%*d = %s" [string length $max] $i [prime::factors.rendered $i]]
}</langsyntaxhighlight>
 
=={{header|VBScript}}==
Made minor modifications on the code I posted under Prime Decomposition.
<langsyntaxhighlight lang="vb">Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Line 2,878 ⟶ 5,102:
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine</langsyntaxhighlight>
 
{{Out}}
Line 2,885 ⟶ 5,109:
2144 = 2 * 2 * 2 * 2 * 2 * 67
</pre>
 
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module CountingInFactors
 
Sub Main()
Line 2,929 ⟶ 5,152:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>
Line 2,952 ⟶ 5,175:
9999 = 3 x 3 x 11 x 101
10000 = 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn main() {
println("1: 1")
for i := 2; ; i++ {
print("$i: ")
mut x := ''
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
print('$x$f')
x = "×"
n /= f
}
}
println('')
}
}</syntaxhighlight>
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2×2
5: 5
6: 2×3
7: 7
8: 2×2×2
9: 3×3
10: 2×5
...
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "./math" for Int
 
for (r in [1..9, 2144..2154, 9987..9999]) {
for (i in r) {
var factors = (i > 1) ? Int.primeFactors(i) : [1]
System.print("%(i): %(factors.join(" x "))")
}
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
1: 1
2: 2
3: 3
4: 2 x 2
5: 5
6: 2 x 3
7: 7
8: 2 x 2 x 2
9: 3 x 3
 
2144: 2 x 2 x 2 x 2 x 2 x 67
2145: 3 x 5 x 11 x 13
2146: 2 x 29 x 37
2147: 19 x 113
2148: 2 x 2 x 3 x 179
2149: 7 x 307
2150: 2 x 5 x 5 x 43
2151: 3 x 3 x 239
2152: 2 x 2 x 2 x 269
2153: 2153
2154: 2 x 3 x 359
 
9987: 3 x 3329
9988: 2 x 2 x 11 x 227
9989: 7 x 1427
9990: 2 x 3 x 3 x 3 x 5 x 37
9991: 97 x 103
9992: 2 x 2 x 2 x 1249
9993: 3 x 3331
9994: 2 x 19 x 263
9995: 5 x 1999
9996: 2 x 2 x 3 x 7 x 7 x 17
9997: 13 x 769
9998: 2 x 4999
9999: 3 x 3 x 11 x 101
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int N0, N, F;
[N0:= 1;
Line 2,971 ⟶ 5,277:
N0:= N0+1;
until KeyHit;
]</langsyntaxhighlight>
 
Example output:
Line 3,009 ⟶ 5,315:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">foreach n in ([1..*]){ println(n,": ",primeFactors(n).concat("\U2715;")) }</langsyntaxhighlight>
Using the fixed size integer (64 bit) solution from [[Prime decomposition#zkl]]
<langsyntaxhighlight lang="zkl">fcn primeFactors(n){ // Return a list of factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
Line 3,023 ⟶ 5,329:
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,039 ⟶ 5,345:
...
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<syntaxhighlight lang="zxbasic">10 FOR i=1 TO 20
20 PRINT i;" = ";
30 IF i=1 THEN PRINT 1: GO TO 90
40 LET p=2: LET n=i: LET f$=""
50 IF p>n THEN GO TO 80
60 IF NOT FN m(n,p) THEN LET f$=f$+STR$ p+" x ": LET n=INT (n/p): GO TO 50
70 LET p=p+1: GO TO 50
80 PRINT f$( TO LEN f$-3)
90 NEXT i
100 STOP
110 DEF FN m(a,b)=a-INT (a/b)*b</syntaxhighlight>
2,114

edits