Aliquot sequence classifications: Difference between revisions

→‎{{header|REXX}}: make it ooRexx compatible and readable
(→‎{{header|REXX}}: make it ooRexx compatible and readable)
(47 intermediate revisions by 22 users not shown)
Line 31:
*   [[Amicable pairs]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F pdsum(n)
R sum((1 .. (n + 1) I/ 2).filter(x -> @n % x == 0 & @n != x))
 
F aliquot(n, maxlen = 16, maxterm = 2 ^ 30)
I n == 0
R (‘terminating’, [0])
V s = [n]
V slen = 1
V new = n
L slen <= maxlen & new < maxterm
new = pdsum(s.last)
I new C s
I s[0] == new
I slen == 1
R (‘perfect’, s)
E I slen == 2
R (‘amicable’, s)
E
R (‘sociable of length #.’.format(slen), s)
E I s.last == new
R (‘aspiring’, s)
E
R (‘cyclic back to #.’.format(new), s)
E I new == 0
R (‘terminating’, s [+] [0])
E
s.append(new)
slen++
L.was_no_break
R (‘non-terminating’, s)
 
L(n) 1..10
V (cls, seq) = aliquot(n)
print(‘#.: #.’.format(cls, seq))
print()
L(n) [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]
V (cls, seq) = aliquot(n)
print(‘#.: #.’.format(cls, seq))</syntaxhighlight>
 
{{out}}
<pre>
terminating: [1, 0]
terminating: [2, 1, 0]
terminating: [3, 1, 0]
terminating: [4, 3, 1, 0]
terminating: [5, 1, 0]
perfect: [6]
terminating: [7, 1, 0]
terminating: [8, 7, 1, 0]
terminating: [9, 4, 3, 1, 0]
terminating: [10, 8, 7, 1, 0]
 
terminating: [11, 1, 0]
terminating: [12, 16, 15, 9, 4, 3, 1, 0]
perfect: [28]
perfect: [496]
amicable: [220, 284]
amicable: [1184, 1210]
sociable of length 5: [12496, 14288, 15472, 14536, 14264]
sociable of length 4: [1264460, 1547860, 1727636, 1305184]
aspiring: [790, 650, 652, 496]
aspiring: [909, 417, 143, 25, 6]
cyclic back to 284: [562, 284, 220]
cyclic back to 1184: [1064, 1336, 1184, 1210]
non-terminating: [1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384, 1474608]
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program aliquotSeq64.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
.equ MAXINUM, 10
.equ MAXI, 16
.equ NBDIVISORS, 1000
 
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program 64 bits start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessErrorArea: .asciz "\033[31mError : area divisors too small.\033[0m \n"
szMessError: .asciz "\033[31m\nError !!!\033[0m \n"
szMessErrGen: .asciz "\033[31mError end program.\033[0m \n"
szMessOverflow: .asciz "\033[31mOverflow function isPrime.\033[0m \n"
 
szCarriageReturn: .asciz "\n"
szLibPerf: .asciz "Perfect \n"
szLibAmic: .asciz "Amicable \n"
szLibSoc: .asciz "Sociable \n"
szLibAspi: .asciz "Aspiring \n"
szLibCycl: .asciz "Cyclic \n"
szLibTerm: .asciz "Terminating \n"
szLibNoTerm: .asciz "No terminating\n"
 
/* datas message display */
szMessResult: .asciz " @ "
szMessResHead: .asciz "Number @ :"
 
.align 4
tbNumber: .quad 11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488
.equ NBNUMBER, (. - tbNumber ) / 8
 
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
sZoneConv: .skip 24
tbZoneDecom: .skip 8 * NBDIVISORS // facteur 4 octets
tbNumberSucc: .skip 8 * MAXI
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // program start
ldr x0,qAdrszMessStartPgm // display start message
bl affichageMess
 
mov x4,#1
1:
mov x0,x4 // number
bl aliquotClassif // aliquot classification
cmp x0,#-1 // error ?
beq 99f
add x4,x4,#1
cmp x4,#MAXINUM
ble 1b
ldr x5,qAdrtbNumber // number array
mov x4,#0
2:
ldr x0,[x5,x4,lsl #3] // load a number
bl aliquotClassif // aliquot classification
cmp x0,#-1 // error ?
beq 99f
add x4,x4,#1 // next number
cmp x4,#NBNUMBER // maxi ?
blt 2b // no -> loop
ldr x0,qAdrszMessEndPgm // display end message
bl affichageMess
b 100f
99: // display error message
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrszMessStartPgm: .quad szMessStartPgm
qAdrszMessEndPgm: .quad szMessEndPgm
qAdrszMessError: .quad szMessError
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrtbZoneDecom: .quad tbZoneDecom
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
qAdrtbNumber: .quad tbNumber
/******************************************************************/
/* function aliquot classification */
/******************************************************************/
/* x0 contains number */
aliquotClassif:
stp x4,lr,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
stp x7,x8,[sp,-16]! // save registres
mov x5,x0 // save number
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
strb wzr,[x1,x0]
ldr x0,qAdrszMessResHead
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // put in head message
bl affichageMess // and display
mov x0,x5 // restaur number
ldr x7,qAdrtbNumberSucc // number successif array
mov x4,#0 // counter number successif
1:
mov x6,x0 // previous number
ldr x1,qAdrtbZoneDecom
bl decompFact // create area of divisors
cmp x0,#0 // error ?
blt 99f
sub x3,x1,x6 // sum
mov x0,x3
ldr x1,qAdrsZoneConv
bl conversion10 // convert ascii string
strb wzr,[x1,x0]
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and put in message
bl affichageMess
cmp x3,#0 // sum = zero
bne 11f
ldr x0,qAdrszLibTerm // terminating
bl affichageMess
b 100f
11:
cmp x5,x3 // compare number and sum
bne 4f
cmp x4,#0 // first loop ?
bne 2f
ldr x0,qAdrszLibPerf // perfect
bl affichageMess
b 100f
2:
cmp x4,#1 // second loop ?
bne 3f
ldr x0,qAdrszLibAmic // amicable
bl affichageMess
b 100f
3: // other loop
ldr x0,qAdrszLibSoc // sociable
bl affichageMess
b 100f
4:
cmp x6,x3 // compare sum and (sum - 1)
bne 5f
ldr x0,qAdrszLibAspi // aspirant
bl affichageMess
b 100f
5:
cmp x3,#1 // if one ,no search in array
beq 7f
mov x2,#0 // search indice
6: // search number in array
ldr x9,[x7,x2,lsl #3]
cmp x9,x3 // equal ?
beq 8f // yes -> cycling
add x2,x2,#1 // increment indice
cmp x2,x4 // end ?
blt 6b // no -> loop
7:
cmp x4,#MAXI
blt 10f
ldr x0,qAdrszLibNoTerm // no terminating
bl affichageMess
b 100f
8: // cycling
ldr x0,qAdrszLibCycl
bl affichageMess
b 100f
10:
str x3,[x7,x4,lsl #3] // store new sum in array
add x4,x4,#1 // increment counter
mov x0,x3 // new number = new sum
b 1b // and loop
99: // display error
ldr x0,qAdrszMessError
bl affichageMess
mov x0,-1
100:
ldp x7,x8,[sp],16 // restaur des 2 registres
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x4,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessResHead: .quad szMessResHead
qAdrszLibPerf: .quad szLibPerf
qAdrszLibAmic: .quad szLibAmic
qAdrszLibSoc: .quad szLibSoc
qAdrszLibCycl: .quad szLibCycl
qAdrszLibAspi: .quad szLibAspi
qAdrszLibNoTerm: .quad szLibNoTerm
qAdrszLibTerm: .quad szLibTerm
qAdrtbNumberSucc: .quad tbNumberSucc
/******************************************************************/
/* decomposition en facteur */
/******************************************************************/
/* x0 contient le nombre à decomposer */
/* x1 contains factor area address */
decompFact:
stp x3,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
stp x10,x11,[sp,-16]! // save registres
mov x5,x1
mov x1,x0
cmp x0,1
beq 100f
mov x8,x0 // save number
bl isPrime // prime ?
cmp x0,#1
beq 98f // yes is prime
mov x1,#1
str x1,[x5] // first factor
mov x12,#1 // divisors sum
mov x4,#1 // indice divisors table
mov x1,#2 // first divisor
mov x6,#0 // previous divisor
mov x7,#0 // number of same divisors
2:
mov x0,x8 // dividende
udiv x2,x0,x1 // x1 divisor x2 quotient x3 remainder
msub x3,x2,x1,x0
cmp x3,#0
bne 5f // if remainder <> zero -> no divisor
mov x8,x2 // else quotient -> new dividende
cmp x1,x6 // same divisor ?
beq 4f // yes
mov x7,x4 // number factors in table
mov x9,#0 // indice
21:
ldr x10,[x5,x9,lsl #3 ] // load one factor
mul x10,x1,x10 // multiply
str x10,[x5,x7,lsl #3] // and store in the table
adds x12,x12,x10
bcs 99f
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 21b
mov x4,x7
mov x6,x1 // new divisor
b 7f
4: // same divisor
sub x9,x4,#1
mov x7,x4
41:
ldr x10,[x5,x9,lsl #3 ]
cmp x10,x1
sub x13,x9,1
csel x9,x13,x9,ne
bne 41b
sub x9,x4,x9
42:
ldr x10,[x5,x9,lsl #3 ]
mul x10,x1,x10
str x10,[x5,x7,lsl #3] // and store in the table
adds x12,x12,x10
bcs 99f
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 42b
mov x4,x7
b 7f // and loop
/* not divisor -> increment next divisor */
5:
cmp x1,#2 // if divisor = 2 -> add 1
add x13,x1,#1 // add 1
add x14,x1,#2 // else add 2
csel x1,x13,x14,eq
b 2b
/* divisor -> test if new dividende is prime */
7:
mov x3,x1 // save divisor
cmp x8,#1 // dividende = 1 ? -> end
beq 10f
mov x0,x8 // new dividende is prime ?
mov x1,#0
bl isPrime // the new dividende is prime ?
cmp x0,#1
bne 10f // the new dividende is not prime
cmp x8,x6 // else dividende is same divisor ?
beq 9f // yes
mov x7,x4 // number factors in table
mov x9,#0 // indice
71:
ldr x10,[x5,x9,lsl #3 ] // load one factor
mul x10,x8,x10 // multiply
str x10,[x5,x7,lsl #3] // and store in the table
adds x12,x12,x10
bcs 99f
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 71b
mov x4,x7
mov x7,#0
b 11f
9:
sub x9,x4,#1
mov x7,x4
91:
ldr x10,[x5,x9,lsl #3 ]
cmp x10,x8
sub x13,x9,#1
csel x9,x13,x9,ne
bne 91b
sub x9,x4,x9
92:
ldr x10,[x5,x9,lsl #3 ]
mul x10,x8,x10
str x10,[x5,x7,lsl #3] // and store in the table
adds x12,x12,x10
bcs 99f // overflow
add x7,x7,#1 // and increment counter
add x9,x9,#1
cmp x9,x4
blt 92b
mov x4,x7
b 11f
10:
mov x1,x3 // current divisor = new divisor
cmp x1,x8 // current divisor > new dividende ?
ble 2b // no -> loop
/* end decomposition */
11:
mov x0,x4 // return number of table items
mov x1,x12 // return sum
mov x3,#0
str x3,[x5,x4,lsl #3] // store zéro in last table item
b 100f
98:
add x1,x8,1
mov x0,#0 // return code
b 100f
99:
ldr x0,qAdrszMessError
bl affichageMess
mov x0,#-1 // error code
b 100f
 
 
100:
ldp x10,x11,[sp],16 // restaur des 2 registres
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x3,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrszMessErrGen: .quad szMessErrGen
/***************************************************/
/* Verification si un nombre est premier */
/***************************************************/
/* x0 contient le nombre à verifier */
/* x0 retourne 1 si premier 0 sinon */
isPrime:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
sub x1,x0,#1
cmp x2,0
beq 99f // retourne zéro
cmp x2,2 // pour 1 et 2 retourne 1
ble 2f
mov x0,#2
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,3
beq 2f
mov x0,#3
bl moduloPux64
blt 100f // erreur overflow
cmp x0,#1
bne 99f
 
cmp x2,5
beq 2f
mov x0,#5
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
 
cmp x2,7
beq 2f
mov x0,#7
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
 
cmp x2,11
beq 2f
mov x0,#11
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
 
cmp x2,13
beq 2f
mov x0,#13
bl moduloPux64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
2:
cmn x0,0 // carry à zero pas d'erreur
mov x0,1 // premier
b 100f
99:
cmn x0,0 // carry à zero pas d'erreur
mov x0,#0 // Pas premier
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
 
/**************************************************************/
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/********************************************************/
/* x0 nombre */
/* x1 exposant */
/* x2 modulo */
moduloPux64:
stp x1,lr,[sp,-16]! // save registres
stp x3,x4,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
stp x7,x8,[sp,-16]! // save registres
stp x9,x10,[sp,-16]! // save registres
cbz x0,100f
cbz x1,100f
mov x8,x0
mov x7,x1
mov x6,1 // resultat
udiv x4,x8,x2
msub x9,x4,x2,x8 // contient le reste
1:
tst x7,1
beq 2f
mul x4,x9,x6
umulh x5,x9,x6
mov x6,x4
mov x0,x6
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x6,x3
2:
mul x8,x9,x9
umulh x5,x9,x9
mov x0,x8
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x9,x3
lsr x7,x7,1
cbnz x7,1b
mov x0,x6 // result
cmn x0,0 // carry à zero pas d'erreur
b 100f
99:
ldr x0,qAdrszMessOverflow
bl affichageMess
cmp x0,0 // carry à un car erreur
mov x0,-1 // code erreur
 
100:
ldp x9,x10,[sp],16 // restaur des 2 registres
ldp x7,x8,[sp],16 // restaur des 2 registres
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x3,x4,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrszMessOverflow: .quad szMessOverflow
/***************************************************/
/* division d un nombre de 128 bits par un nombre de 64 bits */
/***************************************************/
/* x0 contient partie basse dividende */
/* x1 contient partie haute dividente */
/* x2 contient le diviseur */
/* x0 retourne partie basse quotient */
/* x1 retourne partie haute quotient */
/* x3 retourne le reste */
divisionReg128U:
stp x6,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x5,#0 // raz du reste R
mov x3,#128 // compteur de boucle
mov x4,#0 // dernier bit
1:
lsl x5,x5,#1 // on decale le reste de 1
tst x1,1<<63 // test du bit le plus à gauche
lsl x1,x1,#1 // on decale la partie haute du quotient de 1
beq 2f
orr x5,x5,#1 // et on le pousse dans le reste R
2:
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 3f
orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute
3:
orr x0,x0,x4 // position du dernier bit du quotient
mov x4,#0 // raz du bit
cmp x5,x2
blt 4f
sub x5,x5,x2 // on enleve le diviseur du reste
mov x4,#1 // dernier bit à 1
4:
// et boucle
subs x3,x3,#1
bgt 1b
lsl x1,x1,#1 // on decale le quotient de 1
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 5f
orr x1,x1,#1
5:
orr x0,x0,x4 // position du dernier bit du quotient
mov x3,x5
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x6,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
 
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Program 64 bits start
Number 1 : 0 Terminating
Number 2 : 1 0 Terminating
Number 3 : 1 0 Terminating
Number 4 : 3 1 0 Terminating
Number 5 : 1 0 Terminating
Number 6 : 6 Perfect
Number 7 : 1 0 Terminating
Number 8 : 7 1 0 Terminating
Number 9 : 4 3 1 0 Terminating
Number 10 : 8 7 1 0 Terminating
Number 11 : 1 0 Terminating
Number 12 : 16 15 9 4 3 1 0 Terminating
Number 28 : 28 Perfect
Number 496 : 496 Perfect
Number 220 : 284 220 Amicable
Number 1184 : 1210 1184 Amicable
Number 12496 : 14288 15472 14536 14264 12496 Sociable
Number 1264460 : 1547860 1727636 1305184 1264460 Sociable
Number 790 : 650 652 496 496 Aspiring
Number 909 : 417 143 25 6 6 Aspiring
Number 562 : 284 220 284 Cyclic
Number 1064 : 1336 1184 1210 1184 Cyclic
Number 1488 : 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608 2461648 No terminating
Program normal end.
</pre>
 
=={{header|ALGOL 68}}==
Assumes LONG INT is at least 64 bits, as in Algol 68G.
<langsyntaxhighlight lang="algol68">BEGIN
# aliquot sequence classification #
# maximum sequence length we consider #
Line 139 ⟶ 796:
print( ( newline ) )
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 168 ⟶ 825:
</pre>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">on aliquotSum(n)
if (n < 2) then return 0
set sum to 1
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set sum to sum + limit
set limit to limit - 1
end if
repeat with i from 2 to limit
if (n mod i is 0) then set sum to sum + i + n div i
end repeat
return sum
end aliquotSum
 
on aliquotSequence(k, maxLength, maxN)
-- Generate the sequence within the specified limitations.
set sequence to {k}
set n to k
repeat (maxLength - 1) times
set n to aliquotSum(n)
set repetition to (sequence contains n)
if (repetition) then exit repeat
set end of sequence to n
if ((n = 0) or (n > maxN)) then exit repeat
end repeat
-- Analyse it.
set sequenceLength to (count sequence)
if (sequenceLength is 1) then
set classification to "perfect"
else if (n is 0) then
set classification to "terminating"
else if (n = k) then
if (sequenceLength is 2) then
set classification to "amicable"
else
set classification to "sociable"
end if
else if (repetition) then
if (sequence ends with n) then
set classification to "aspiring"
else
set classification to "cyclic"
end if
else
set classification to "non-terminating"
end if
return {sequence:sequence, classification:classification}
end aliquotSequence
 
-- Task code:
local output, maxLength, maxN, spacing, astid, k
set output to {""}
set {maxLength, maxN} to {16, 2 ^ 47}
set spacing to " "
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
repeat with k in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ¬
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 1.535571778608E+13}
set thisResult to aliquotSequence(k's contents, maxLength, maxN)
set end of output to text -18 thru -1 of (spacing & k) & ": " & ¬
text 1 thru 17 of (thisResult's classification & spacing) & thisResult's sequence
end repeat
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"
1: terminating 1, 0
2: terminating 2, 1, 0
3: terminating 3, 1, 0
4: terminating 4, 3, 1, 0
5: terminating 5, 1, 0
6: perfect 6
7: terminating 7, 1, 0
8: terminating 8, 7, 1, 0
9: terminating 9, 4, 3, 1, 0
10: terminating 10, 8, 7, 1, 0
11: terminating 11, 1, 0
12: terminating 12, 16, 15, 9, 4, 3, 1, 0
28: perfect 28
496: perfect 496
220: amicable 220, 284
1184: amicable 1184, 1210
12496: sociable 12496, 14288, 15472, 14536, 14264
1264460: sociable 1264460, 1547860, 1727636, 1305184
790: aspiring 790, 650, 652, 496
909: aspiring 909, 417, 143, 25, 6
562: cyclic 562, 284, 220
1064: cyclic 1064, 1336, 1184, 1210
1488: non-terminating 1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384
1.535571778608E+13: non-terminating 1.535571778608E+13, 4.453466360112E+13, 1.449400874645E+14"</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program aliquotSeq.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 MAXINUM, 10
.equ MAXI, 16
.equ NBDIVISORS, 1000
 
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStartPgm: .asciz "Program start \n"
szMessEndPgm: .asciz "Program normal end.\n"
szMessErrorArea: .asciz "\033[31mError : area divisors too small.\033[0m \n"
szMessError: .asciz "\033[31mError !!!\033[0m \n"
szMessErrGen: .asciz "Error end program.\033[0m \n"
 
szCarriageReturn: .asciz "\n"
szLibPerf: .asciz "Perfect \n"
szLibAmic: .asciz "Amicable \n"
szLibSoc: .asciz "Sociable \n"
szLibAspi: .asciz "Aspiring \n"
szLibCycl: .asciz "Cyclic \n"
szLibTerm: .asciz "Terminating \n"
szLibNoTerm: .asciz "No terminating\n"
 
/* datas message display */
szMessResult: .asciz " @ "
szMessResHead: .asciz "Number @ :"
 
.align 4
tbNumber: .int 11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488
.equ NBNUMBER, (. - tbNumber ) / 4
 
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
sZoneConv: .skip 24
tbZoneDecom: .skip 4 * NBDIVISORS // facteur 4 octets
tbNumberSucc: .skip 4 * MAXI
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: @ program start
ldr r0,iAdrszMessStartPgm @ display start message
bl affichageMess
 
mov r4,#1
1:
mov r0,r4 @ number
bl aliquotClassif @ aliquot classification
cmp r0,#-1 @ error ?
beq 99f
add r4,r4,#1
cmp r4,#MAXINUM
ble 1b
ldr r5,iAdrtbNumber @ number array
mov r4,#0
2:
ldr r0,[r5,r4,lsl #2] @ load a number
bl aliquotClassif @ aliquot classification
cmp r0,#-1 @ error ?
beq 99f
add r4,r4,#1 @ next number
cmp r4,#NBNUMBER @ maxi ?
blt 2b @ no -> loop
ldr r0,iAdrszMessEndPgm @ display end message
bl affichageMess
b 100f
99: @ display error message
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessStartPgm: .int szMessStartPgm
iAdrszMessEndPgm: .int szMessEndPgm
iAdrszMessError: .int szMessError
iAdrszCarriageReturn: .int szCarriageReturn
iAdrtbZoneDecom: .int tbZoneDecom
iAdrszMessResult: .int szMessResult
iAdrsZoneConv: .int sZoneConv
iAdrtbNumber: .int tbNumber
/******************************************************************/
/* function aliquot classification */
/******************************************************************/
/* r0 contains number */
aliquotClassif:
push {r3-r8,lr} @ save registers
mov r5,r0 @ save number
ldr r1,iAdrsZoneConv
bl conversion10 @ convert ascii string
mov r2,#0
strb r2,[r1,r0]
ldr r0,iAdrszMessResHead
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ put in head message
bl affichageMess @ and display
mov r0,r5 @ restaur number
ldr r7,iAdrtbNumberSucc @ number successif array
mov r4,#0 @ counter number successif
1:
mov r6,r0 @ previous number
ldr r1,iAdrtbZoneDecom
bl decompFact @ create area of divisors
cmp r0,#0 @ error ?
blt 99f
sub r3,r1,r6 @ sum
mov r0,r3
ldr r1,iAdrsZoneConv
bl conversion10 @ convert ascii string
mov r2,#0
strb r2,[r1,r0]
ldr r0,iAdrszMessResult
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ and put in message
bl affichageMess
cmp r3,#0 @ sum = zero
bne 11f
ldr r0,iAdrszLibTerm @ terminating
bl affichageMess
b 100f
11:
cmp r5,r3 @ compare number and sum
bne 4f
cmp r4,#0 @ first loop ?
bne 2f
ldr r0,iAdrszLibPerf @ perfect
bl affichageMess
b 100f
2:
cmp r4,#1 @ second loop ?
bne 3f
ldr r0,iAdrszLibAmic @ amicable
bl affichageMess
b 100f
3: @ other loop
ldr r0,iAdrszLibSoc @ sociable
bl affichageMess
b 100f
4:
cmp r6,r3 @ compare sum and (sum - 1)
bne 5f
ldr r0,iAdrszLibAspi @ aspirant
bl affichageMess
b 100f
5:
cmp r3,#1 @ if one ,no search in array
beq 7f
mov r2,#0 @ search indice
6: @ search number in array
ldr r8,[r7,r2,lsl #2]
cmp r8,r3 @ equal ?
beq 8f @ yes -> cycling
add r2,r2,#1 @ increment indice
cmp r2,r4 @ end ?
blt 6b @ no -> loop
7:
cmp r4,#MAXI
blt 10f
ldr r0,iAdrszLibNoTerm @ no terminating
bl affichageMess
b 100f
8: @ cycling
ldr r0,iAdrszLibCycl
bl affichageMess
b 100f
10:
str r3,[r7,r4,lsl #2] @ store new sum in array
add r4,r4,#1 @ increment counter
mov r0,r3 @ new number = new sum
b 1b @ and loop
99: @ display error
ldr r0,iAdrszMessError
bl affichageMess
100:
pop {r3-r8,lr} @ restaur registers
bx lr
iAdrszMessResHead: .int szMessResHead
iAdrszLibPerf: .int szLibPerf
iAdrszLibAmic: .int szLibAmic
iAdrszLibSoc: .int szLibSoc
iAdrszLibCycl: .int szLibCycl
iAdrszLibAspi: .int szLibAspi
iAdrszLibNoTerm: .int szLibNoTerm
iAdrszLibTerm: .int szLibTerm
iAdrtbNumberSucc: .int tbNumberSucc
/******************************************************************/
/* factor decomposition */
/******************************************************************/
/* r0 contains number */
/* r1 contains address of divisors area */
/* r0 return divisors items in array */
/* r1 return the sum of divisors */
decompFact:
push {r3-r12,lr} @ save registers
cmp r0,#1
moveq r1,#1
beq 100f
mov r5,r1
mov r8,r0 @ save number
bl isPrime @ prime ?
cmp r0,#1
beq 98f @ yes is prime
mov r1,#1
str r1,[r5] @ first factor
mov r12,#1 @ divisors sum
mov r10,#1 @ indice divisors table
mov r9,#2 @ first divisor
mov r6,#0 @ previous divisor
mov r7,#0 @ number of same divisors
/* division loop */
2:
mov r0,r8 @ dividende
mov r1,r9 @ divisor
bl division @ r2 quotient r3 remainder
cmp r3,#0
beq 3f @ if remainder zero -> divisor
/* not divisor -> increment next divisor */
cmp r9,#2 @ if divisor = 2 -> add 1
addeq r9,#1
addne r9,#2 @ else add 2
b 2b
/* divisor compute the new factors of number */
3:
mov r8,r2 @ else quotient -> new dividende
cmp r9,r6 @ same divisor ?
beq 4f @ yes
mov r0,r5 @ table address
mov r1,r10 @ number factors in table
mov r2,r9 @ divisor
mov r3,r12 @ somme
mov r4,#0
bl computeFactors
cmp r0,#-1
beq 100f
mov r10,r1
mov r12,r0
mov r6,r9 @ new divisor
b 7f
4: @ same divisor
sub r7,r10,#1
5: @ search in table the first use of divisor
ldr r3,[r5,r7,lsl #2 ]
cmp r3,r9
subne r7,#1
bne 5b
@ and compute new factors after factors
sub r4,r10,r7 @ start indice
mov r0,r5
mov r1,r10
mov r2,r9 @ divisor
mov r3,r12
bl computeFactors
cmp r0,#-1
beq 100f
mov r12,r0
mov r10,r1
 
/* divisor -> test if new dividende is prime */
7:
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 8f @ yes
mov r0,r5
mov r1,r10
mov r2,r8
mov r3,r12
mov r4,#0
bl computeFactors
cmp r0,#-1
beq 100f
mov r12,r0
mov r10,r1
mov r7,#0
b 11f
8:
sub r7,r10,#1
9:
ldr r3,[r5,r7,lsl #2 ]
cmp r3,r8
subne r7,#1
bne 9b
mov r0,r5
mov r1,r10
sub r4,r10,r7
mov r2,r8
mov r3,r12
bl computeFactors
cmp r0,#-1
beq 100f
mov r12,r0
mov r10,r1
b 11f
10:
cmp r9,r8 @ current divisor > new dividende ?
ble 2b @ no -> loop
/* end decomposition */
11:
mov r0,r10 @ return number of table items
mov r1,r12 @ return sum
mov r3,#0
str r3,[r5,r10,lsl #2] @ store zéro in last table item
b 100f
 
98: @ prime number
add r1,r8,#1
mov r0,#0 @ return code
b 100f
99:
ldr r0,iAdrszMessError
bl affichageMess
mov r0,#-1 @ error code
b 100f
100:
pop {r3-r12,pc} @ restaur registers
/******************************************************************/
/* compute all factors */
/******************************************************************/
 
/* r0 table factors address */
/* r1 number factors in table */
/* r2 new divisor */
/* r3 sum */
/* r4 start indice */
/* r0 return sum */
/* r1 return number factors in table */
computeFactors:
push {r2-r6,lr} @ save registers
mov r6,r1 @ number factors in table
1:
ldr r5,[r0,r4,lsl #2 ] @ load one factor
mul r5,r2,r5 @ multiply
str r5,[r0,r1,lsl #2] @ and store in the table
 
adds r3,r5
movcs r0,#-1 @ overflow
bcs 100f
add r1,r1,#1 @ and increment counter
add r4,r4,#1
cmp r4,r6
blt 1b
mov r0,r3 @ factors sum
100: @ fin standard de la fonction
pop {r2-r6,pc} @ restaur des registres
/***************************************************/
/* check if a number is prime */
/***************************************************/
/* r0 contains the number */
/* r0 return 1 if prime 0 else */
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,pc} @ restaur des registres
/********************************************************/
/* 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 @ TODO: v鲩fier les cas d erreur
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,pc} @ restaur des registres
 
/***************************************************/
/* 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駡tive ?
@ 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,pc} @ restaur registers
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
 
</syntaxhighlight>
<pre>
Program start
Number 1 : 0 Terminating
Number 2 : 1 0 Terminating
Number 3 : 1 0 Terminating
Number 4 : 3 1 0 Terminating
Number 5 : 1 0 Terminating
Number 6 : 6 Perfect
Number 7 : 1 0 Terminating
Number 8 : 7 1 0 Terminating
Number 9 : 4 3 1 0 Terminating
Number 10 : 8 7 1 0 Terminating
Number 11 : 1 0 Terminating
Number 12 : 16 15 9 4 3 1 0 Terminating
Number 28 : 28 Perfect
Number 496 : 496 Perfect
Number 220 : 284 220 Amicable
Number 1184 : 1210 1184 Amicable
Number 12496 : 14288 15472 14536 14264 12496 Sociable
Number 1264460 : 1547860 1727636 1305184 1264460 Sociable
Number 790 : 650 652 496 496 Aspiring
Number 909 : 417 143 25 6 6 Aspiring
Number 562 : 284 220 284 Cyclic
Number 1064 : 1336 1184 1210 1184 Cyclic
Number 1488 : 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608 2461648 No terminating
Program normal end.
</pre>
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">
#!/bin/gawk -f
function sumprop(num, i,sum,root) {
Line 238 ⟶ 1,568:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 268 ⟶ 1,598:
 
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256"># Rosetta Code problem: http://rosettacode.org/wiki/Aliquot_sequence_classifications
# by Jjuanhdez, 06/2022
 
global limite
limite = 20000000
 
dim nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}
 
for n = 0 to nums[?]-1
print "Number "; nums[n]; " : ";
call PrintAliquotClassifier(nums[n])
next n
print
print "Program normal end."
end
 
function PDtotal (n)
total = 0
for y = 2 to n
if (n mod y) = 0 then total += (n / y)
next y
return total
end function
 
subroutine PrintAliquotClassifier (K)
longit = 52: n = K: clase = 0: priorn = 0: inc = 0
dim Aseq(longit)
 
for element = 2 to longit
Aseq[element] = PDtotal(n)
n = int(Aseq[element])
print n; " ";
begin case
case n = 0
print " Terminating": clase = 1: exit for
case n = K and element = 2
print " Perfect" : clase = 2: exit for
case n = K and element = 3
print " Amicable": clase = 3: exit for
case n = K and element > 3
print " Sociable": clase = 4: exit for
case n <> K and Aseq[element - 1] = Aseq[element]
print " Aspiring": clase = 5: exit for
case n <> K and Aseq[element - 2] = n
print " Cyclic": clase = 6: exit for
end case
 
if n > priorn then priorn = n: inc += 1 else inc = 0: priorn = 0
if inc = 11 or n > limite then exit for
next element
if clase = 0 then print " non-terminating"
end subroutine</syntaxhighlight>
 
=={{header|C}}==
Line 273 ⟶ 1,659:
===Brute Force===
The following implementation is a brute force method which takes a very, very long time for 15355717786080. To be fair to C, that's also true for many of the other implementations on this page which also implement the brute force method. See the next implementation for the best solution.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<string.h>
Line 345 ⟶ 1,731:
return 0;
}
</syntaxhighlight>
</lang>
Input file, you can include 15355717786080 or similar numbers in this list but be prepared to wait for a very, very long time.:
<pre>
Line 406 ⟶ 1,792:
===Number Theoretic===
The following implementation, based on Number Theory, is the best solution for such a problem. All cases are handled, including 15355717786080, with all the numbers being processed and the output written to console practically instantaneously. The above brute force implementation is the original one and it remains to serve as a comparison of the phenomenal difference the right approach can make to a problem.
<syntaxhighlight lang="c">
<lang C>
#include<string.h>
#include<stdlib.h>
Line 508 ⟶ 1,894:
return 0;
}
</syntaxhighlight>
</lang>
Input file, to emphasize the effectiveness of this approach, the last number in the file is 153557177860800, 10 times the special case mentioned in the task.
<pre>
Line 572 ⟶ 1,958:
336056, 1405725265675144, 1230017019320456, 68719476751
</pre>
 
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Linq;
 
public class AliquotSequenceClassifications
{
private static long ProperDivsSum(long n)
{
return Enumerable.Range(1, (int)(n / 2)).Where(i => n % i == 0).Sum(i => (long)i);
}
 
public static bool Aliquot(long n, int maxLen, long maxTerm)
{
List<long> s = new List<long>(maxLen) {n};
long newN = n;
 
while (s.Count <= maxLen && newN < maxTerm)
{
newN = ProperDivsSum(s.Last());
 
if (s.Contains(newN))
{
if (s[0] == newN)
{
switch (s.Count)
{
case 1:
return Report("Perfect", s);
case 2:
return Report("Amicable", s);
default:
return Report("Sociable of length " + s.Count, s);
}
}
else if (s.Last() == newN)
{
return Report("Aspiring", s);
}
else
{
return Report("Cyclic back to " + newN, s);
}
}
else
{
s.Add(newN);
if (newN == 0)
return Report("Terminating", s);
}
}
 
return Report("Non-terminating", s);
}
 
static bool Report(string msg, List<long> result)
{
Console.WriteLine(msg + ": " + string.Join(", ", result));
return false;
}
 
public static void Main(string[] args)
{
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488
};
 
Enumerable.Range(1, 10).ToList().ForEach(n => Aliquot(n, 16, 1L << 47));
Console.WriteLine();
foreach (var n in arr)
{
Aliquot(n, 16, 1L << 47);
}
}
}
</syntaxhighlight>
{{out}}
<pre>
Terminating: 1, 0
Terminating: 2, 1, 0
Terminating: 3, 1, 0
Terminating: 4, 3, 1, 0
Terminating: 5, 1, 0
Perfect: 6
Terminating: 7, 1, 0
Terminating: 8, 7, 1, 0
Terminating: 9, 4, 3, 1, 0
Terminating: 10, 8, 7, 1, 0
 
Terminating: 11, 1, 0
Terminating: 12, 16, 15, 9, 4, 3, 1, 0
Perfect: 28
Perfect: 496
Amicable: 220, 284
Amicable: 1184, 1210
Sociable of length 5: 12496, 14288, 15472, 14536, 14264
Sociable of length 4: 1264460, 1547860, 1727636, 1305184
Aspiring: 790, 650, 652, 496
Aspiring: 909, 417, 143, 25, 6
Cyclic back to 284: 562, 284, 220
Cyclic back to 1184: 1064, 1336, 1184, 1210
Non-terminating: 1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384, 1474608
 
</pre>
 
 
=={{header|C++}}==
This one follows the trail blazed by the "Number Theoretic" C example above.
<syntaxhighlight lang="cpp">#include <cstdint>
#include <iostream>
#include <string>
 
using integer = uint64_t;
 
// See https://en.wikipedia.org/wiki/Divisor_function
integer divisor_sum(integer n) {
integer total = 1, power = 2;
// Deal with powers of 2 first
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
// Odd prime factors up to the square root
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
// If n > 1 then it's prime
if (n > 1)
total *= n + 1;
return total;
}
 
// See https://en.wikipedia.org/wiki/Aliquot_sequence
void classify_aliquot_sequence(integer n) {
constexpr int limit = 16;
integer terms[limit];
terms[0] = n;
std::string classification("non-terminating");
int length = 1;
for (int i = 1; i < limit; ++i) {
++length;
terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];
if (terms[i] == n) {
classification =
(i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable"));
break;
}
int j = 1;
for (; j < i; ++j) {
if (terms[i] == terms[i - j])
break;
}
if (j < i) {
classification = (j == 1 ? "aspiring" : "cyclic");
break;
}
if (terms[i] == 0) {
classification = "terminating";
break;
}
}
std::cout << n << ": " << classification << ", sequence: " << terms[0];
for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)
std::cout << ' ' << terms[i];
std::cout << '\n';
}
 
int main() {
for (integer i = 1; i <= 10; ++i)
classify_aliquot_sequence(i);
for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,
1064, 1488})
classify_aliquot_sequence(i);
classify_aliquot_sequence(15355717786080);
classify_aliquot_sequence(153557177860800);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
1: terminating, sequence: 1 0
2: terminating, sequence: 2 1 0
3: terminating, sequence: 3 1 0
4: terminating, sequence: 4 3 1 0
5: terminating, sequence: 5 1 0
6: perfect, sequence: 6
7: terminating, sequence: 7 1 0
8: terminating, sequence: 8 7 1 0
9: terminating, sequence: 9 4 3 1 0
10: terminating, sequence: 10 8 7 1 0
11: terminating, sequence: 11 1 0
12: terminating, sequence: 12 16 15 9 4 3 1 0
28: perfect, sequence: 28
496: perfect, sequence: 496
220: amicable, sequence: 220 284 220
1184: amicable, sequence: 1184 1210 1184
12496: sociable, sequence: 12496 14288 15472 14536 14264 12496
1264460: sociable, sequence: 1264460 1547860 1727636 1305184 1264460
790: aspiring, sequence: 790 650 652 496
909: aspiring, sequence: 909 417 143 25 6
562: cyclic, sequence: 562 284 220 284
1064: cyclic, sequence: 1064 1336 1184 1210 1184
1488: non-terminating, sequence: 1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384
15355717786080: non-terminating, sequence: 15355717786080 44534663601120 144940087464480 471714103310688 1130798979186912 2688948041357088 6050151708497568 13613157922639968 35513546724070632 74727605255142168 162658586225561832 353930992506879768 642678347124409032 1125102611548462968 1977286128289819992 3415126495450394808
153557177860800: non-terminating, sequence: 153557177860800 470221741508000 685337334283120 908681172226160 1276860840159280 1867115442105104 1751034184622896 1643629718341256 1441432897905784 1647351883321016 1557892692704584 1363939602434936 1194001297910344 1597170567336056 1405725265675144 1230017019320456
</pre>
 
=={{header|CLU}}==
{{trans|C++}}
<syntaxhighlight lang="clu">% This program uses the 'bigint' cluster from PCLU's 'misc.lib'
 
% Remove leading and trailing whitespace (bigint$unparse adds a lot)
strip = proc (s: string) returns (string)
ac = array[char]
sc = sequence[char]
cs: ac := string$s2ac(s)
while ~ac$empty(cs) cand ac$bottom(cs)=' ' do ac$reml(cs) end
while ~ac$empty(cs) cand ac$top(cs)=' ' do ac$remh(cs) end
% There's a bug in ac2s that makes it not return all elements
% This is a workaround
return(string$sc2s(sc$a2s(cs)))
end strip
 
divisor_sum = proc (n: bigint) returns (bigint)
own zero: bigint := bigint$i2bi(0)
own one: bigint := bigint$i2bi(1)
own two: bigint := bigint$i2bi(2)
own three: bigint := bigint$i2bi(3)
total: bigint := one
power: bigint := two
while n//two=zero do
total := total + power
power := power * two
n := n / two
end
p: bigint := three
while p*p <= n do
sum: bigint := one
power := p
while n//p = zero do
sum := sum + power
power := power * p
n := n/p
end
total := total * sum
p := p + two
end
if n>one then total := total * (n+one) end
return(total)
end divisor_sum
 
classify_aliquot_sequence = proc (n: bigint)
LIMIT = 16
abi = array[bigint]
own zero: bigint := bigint$i2bi(0)
po: stream := stream$primary_output()
terms: array[bigint] := abi$predict(0,LIMIT)
abi$addh(terms, n)
classification: string := "non-terminating"
for i: int in int$from_to(1, limit-1) do
abi$addh(terms, divisor_sum(abi$top(terms)) - abi$top(terms))
if abi$top(terms) = n then
if i=1 then classification := "perfect"
elseif i=2 then classification := "amicable"
else classification := "sociable"
end
break
end
j: int := 1
while j<i cand terms[i] ~= terms[i-j] do j := j+1 end
if j<i then
if j=1 then classification := "aspiring"
else classification := "cyclic"
end
break
end
if abi$top(terms) = zero then
classification := "terminating"
break
end
end
stream$puts(po, strip(bigint$unparse(n)) || ": " || classification || ", sequence: "
|| strip(bigint$unparse(terms[0])))
for i: int in int$from_to(1, abi$high(terms)) do
if terms[i] = terms[i-1] then break end
stream$puts(po, " " || strip(bigint$unparse(terms[i])))
end
stream$putl(po, "")
end classify_aliquot_sequence
 
start_up = proc ()
for i: int in int$from_to(1, 10) do
classify_aliquot_sequence(bigint$i2bi(i))
end
for i: int in array[int]$elements(array[int]$
[11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488]) do
classify_aliquot_sequence(bigint$i2bi(i))
end
classify_aliquot_sequence(bigint$parse("15355717786080"))
classify_aliquot_sequence(bigint$parse("153557177860800"))
end start_up</syntaxhighlight>
{{out}}
<pre>1: terminating, sequence: 1 0
2: terminating, sequence: 2 1 0
3: terminating, sequence: 3 1 0
4: terminating, sequence: 4 3 1 0
5: terminating, sequence: 5 1 0
6: perfect, sequence: 6
7: terminating, sequence: 7 1 0
8: terminating, sequence: 8 7 1 0
9: terminating, sequence: 9 4 3 1 0
10: terminating, sequence: 10 8 7 1 0
11: terminating, sequence: 11 1 0
12: terminating, sequence: 12 16 15 9 4 3 1 0
28: perfect, sequence: 28
496: perfect, sequence: 496
220: amicable, sequence: 220 284 220
1184: amicable, sequence: 1184 1210 1184
12496: sociable, sequence: 12496 14288 15472 14536 14264 12496
1264460: sociable, sequence: 1264460 1547860 1727636 1305184 1264460
790: aspiring, sequence: 790 650 652 496
909: aspiring, sequence: 909 417 143 25 6
562: cyclic, sequence: 562 284 220 284
1064: cyclic, sequence: 1064 1336 1184 1210 1184
1488: non-terminating, sequence: 1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384
15355717786080: non-terminating, sequence: 15355717786080 44534663601120 144940087464480 471714103310688 1130798979186912 2688948041357088 6050151708497568 13613157922639968 35513546724070632 74727605255142168 162658586225561832 353930992506879768 642678347124409032 1125102611548462968 1977286128289819992 3415126495450394808
153557177860800: non-terminating, sequence: 153557177860800 470221741508000 685337334283120 908681172226160 1276860840159280 1867115442105104 1751034184622896 1643629718341256 1441432897905784 1647351883321016 1557892692704584 1363939602434936 1194001297910344 1597170567336056 1405725265675144 1230017019320456</pre>
 
=={{header|Common Lisp}}==
Uses the Lisp function '''proper-divisors-recursive''' from [[Proper_divisors#Common_Lisp|Task:Proper Divisors]].
<langsyntaxhighlight lang="lisp">(defparameter *nlimit* 16)
(defparameter *klimit* (expt 2 47))
(defparameter *asht* (make-hash-table))
Line 641 ⟶ 2,364:
(aliquot (+ k 1)))
(dolist (k '(11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080))
(aliquot k)))</langsyntaxhighlight>
{{out}}
<pre>CL-USER(45): (main)
Line 674 ⟶ 2,397:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm, std.typecons, std.conv;
 
auto properDivisors(in ulong n) pure nothrow @safe /*@nogc*/ {
Line 724 ⟶ 2,447:
790, 909, 562, 1064, 1488])
writefln("%s: %s", n.aliquot[]);
}</langsyntaxhighlight>
{{out}}
<pre>Terminating: [1, 0]
Line 750 ⟶ 2,473:
Cyclic back to 1184: [1064, 1336, 1184, 1210]
Non-terminating: [1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384, 1474608]</pre>
 
=={{header|EasyLang}}==
{{trans|AWK}}
<syntaxhighlight lang=easylang>
fastfunc sumprop num .
if num = 1
return 0
.
sum = 1
root = sqrt num
i = 2
while i < root
if num mod i = 0
sum += i + num / i
.
i += 1
.
if num mod root = 0
sum += root
.
return sum
.
func$ tostr ar[] .
for v in ar[]
s$ &= " " & v
.
return s$
.
func$ class k .
oldk = k
newk = sumprop oldk
oldk = newk
seq[] &= newk
if newk = 0
return "terminating " & tostr seq[]
.
if newk = k
return "perfect " & tostr seq[]
.
newk = sumprop oldk
oldk = newk
seq[] &= newk
if newk = 0
return "terminating " & tostr seq[]
.
if newk = k
return "amicable " & tostr seq[]
.
for t = 4 to 16
newk = sumprop oldk
seq[] &= newk
if newk = 0
return "terminating " & tostr seq[]
.
if newk = k
return "sociable (period " & t - 1 & ") " & tostr seq[]
.
if newk = oldk
return "aspiring " & tostr seq[]
.
for i to len seq[] - 1
if newk = seq[i]
return "cyclic (at " & newk & ") " & tostr seq[]
.
.
if newk > 140737488355328
return "non-terminating (term > 140737488355328) " & tostr seq[]
.
oldk = newk
.
return "non-terminating (after 16 terms) " & tostr seq[]
.
print "Number classification sequence"
for j = 1 to 12
print j & " " & class j
.
for j in [ 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 ]
print j & " " & class j
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; implementation of Floyd algorithm to find cycles in a graph
;; see Wikipedia https://en.wikipedia.org/wiki/Cycle_detection
Line 807 ⟶ 2,610:
(when (= x0 starter) (set! end starter)))
(writeln ...))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(lib 'math)
(lib 'bigint)
Line 849 ⟶ 2,652:
1000 terminating
1000 1340 1516 1144 1376 1396 1054 674 340 416 466 236 184 176 196 203 37 1 0 0 ...
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Proper do
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
Line 902 ⟶ 2,705:
if n<10000000, do: :io.fwrite("~7w:~21s: ~p~n", [n, msg, s]),
else: :io.fwrite("~w: ~s: ~p~n", [n, msg, s])
end)</langsyntaxhighlight>
 
{{out}}
Line 938 ⟶ 2,741:
=={{header|Factor}}==
For convenience, the term that caused termination is always included in the output sequence.
<langsyntaxhighlight lang="factor">USING: combinators combinators.short-circuit formatting kernel
literals locals math math.functions math.primes.factors
math.ranges namespaces pair-rocket sequences sets ;
Line 991 ⟶ 2,794:
10 [1,b] test-cases append [ .classify ] each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,055 ⟶ 2,858:
A more flexible syntax (such as Algol's) would enable the double scan of the TRAIL array to be avoided, as in if TRAIL[I:=MinLoc(Abs(TRAIL(1:L) - SF))] = SF then... That is, find the first index of array TRAIL such that ABS(TRAIL(1:L) - SF) is minimal, save that index in I, then access that element of TRAIL and test if it is equal to SF. The INDEX function could be use to find the first match, except that it is defined only for character variables. Alternatively, use an explicit DO-loop to search for equality, thus not employing fancy syntax, and not having to wonder if the ANY function will stop on the first match rather than wastefully continue the testing for all array elements. The modern style in manual writing is to employ vaguely general talk about arrays and omit specific details.
 
<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE FACTORSTUFF !This protocol evades the need for multiple parameters, or COMMON, or one shapeless main line...
Concocted by R.N.McLean, MMXV.
Line 1,179 ⟶ 2,982:
END DO
END !Done.
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
{{trans|C}}
<syntaxhighlight lang="freebasic">function raiseTo( bas as ulongint, power as ulongint ) as ulongint
dim as ulongint result = 1, i
for i = 1 to power
result*=bas
next i
return result
end function
function properDivisorSum( n as ulongint ) as ulongint
dim as ulongint prod = 1, temp = n, i = 3, count = 0
while n mod 2 = 0
count += 1
n /= 2
wend
if count<>0 then prod *= (raiseTo(2,count + 1) - 1)
while i*i <= n
count = 0
while n mod i = 0
count += 1
n /= i
wend
if count = 1 then
prod *= (i+1)
elseif count > 1 then
prod *= ((raiseTo(i,count + 1) - 1)/(i-1))
end if
i += 2
wend
if n>2 then prod *= (n+1)
return prod - temp
end function
sub printSeries( arr() as ulongint ptr, size as integer, ty as string)
dim as integer i
dim as string outstr = "Integer: "+str(arr(0))+", Type: "+ty+", Series: "
for i=0 to size-2
outstr = outstr + str(arr(i))+", "
next i
outstr = outstr + str(arr(i))
print outstr
end sub
sub aliquotClassifier(n as ulongint)
dim as ulongint arr(0 to 15)
dim as integer i, j
dim as string ty = "Sociable"
arr(0) = n
for i = 1 to 15
arr(i) = properDivisorSum(arr(i-1))
if arr(i)=0 orelse arr(i)=n orelse (arr(i) = arr(i-1) and arr(i)<>n) then
if arr(i) = 0 then
ty = "Terminating"
elseif arr(i) = n and i = 1 then
ty = "Perfect"
elseif arr(i) = n and i = 2 then
ty = "Amicable"
elseif arr(i) = arr(i-1) and arr(i)<>n then
ty = "Aspiring"
end if
printSeries(arr(),i+1,ty)
return
end if
for j = 1 to i-1
if arr(j) = arr(i) then
printSeries(arr(),i+1,"Cyclic")
return
end if
next j
next i
printSeries(arr(),i+1,"Non-Terminating")
end sub
 
dim as ulongint nums(0 to 22) = {_
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184,_
12496, 1264460, 790, 909, 562, 1064, 1488}
 
for n as ubyte = 0 to 22
aliquotClassifier(nums(n))
next n</syntaxhighlight>
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,291 ⟶ 3,176:
seq, aliquot := classifySequence(k)
fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}</langsyntaxhighlight>
 
{{out}}
Line 1,326 ⟶ 3,211:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
 
Line 1,366 ⟶ 3,251:
let cls n = let ali = take 16 $ aliquot n in (classify ali, ali)
mapM_ (print . cls) $ [1..10] ++
[11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]</langsyntaxhighlight>
{{out}}
<pre>(Terminating,[1,0])
Line 1,394 ⟶ 3,279:
=={{header|J}}==
Implementation:
<langsyntaxhighlight Jlang="j">proper_divisors=: [: */@>@}:@,@{ [: (^ i.@>:)&.>/ 2 p: x:
aliquot=: +/@proper_divisors ::0:
rc_aliquot_sequence=: aliquot^:(i.16)&>
Line 1,408 ⟶ 3,293:
end.
)
rc_display_aliquot_sequence=: (rc_classify,' ',":)@:rc_aliquot_sequence</langsyntaxhighlight>
 
Task example:
<langsyntaxhighlight Jlang="j"> rc_display_aliquot_sequence&> >: i.10
terminate 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
terminate 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Line 1,437 ⟶ 3,322:
cyclic 1064 1336 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210
non-terminating 1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384
non-terminating 15355717786080 44534663601120 144940087464480 471714103310688 1130798979186912 2688948041357088 6050151708497568 13613157922639968 35513546724070632 74727605255142168 162658586225561832 353930992506879768 642678347124409032 1125102611548462968 1977286128289819992 3415126495450394808</langsyntaxhighlight>
 
=={{header|Java}}==
Translation of [[Aliquot_sequence_classifications#Python|Python]] via [[Aliquot_sequence_classifications#D|D]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Line 1,505 ⟶ 3,390:
Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
}
}</langsyntaxhighlight>
 
<pre>Terminating: [1, 0]
Line 1,535 ⟶ 3,420:
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># "until" is available in more recent versions of jq
# than jq 1.4
def until(cond; next):
Line 1,593 ⟶ 3,478:
790, 909, 562, 1064, 1488, 15355717786080) | pp);
task</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -r -f aliquot.jq
1: terminating: [1,0]
2: terminating: [2,1,0]
Line 1,620 ⟶ 3,505:
1064: cyclic back to 1184: [1064,1336,1184,1210]
1488: non-terminating: [1488,2480,3472,4464,8432,9424,10416,21328,22320,55056,95728,96720,236592,459792,881392,882384]
15355717786080: non-terminating: [15355717786080,44534663601120]</langsyntaxhighlight>
 
=={{header|Julia}}==
'''Core Function'''
<syntaxhighlight lang="julia">
<lang Julia>
function aliquotclassifier{T<:Integer}(n::T)
a = T[n]
Line 1,649 ⟶ 3,534:
return ("Non-terminating", a)
end
</syntaxhighlight>
</lang>
 
'''Supporting Functions'''
<syntaxhighlight lang="julia">
<lang Julia>
function pcontrib{T<:Integer}(p::T, a::T)
n = one(T)
Line 1,670 ⟶ 3,555:
dsum -= n
end
</syntaxhighlight>
</lang>
 
'''Main'''
<langsyntaxhighlight Julialang="julia">using Printf
 
println("Classification Tests:")
Line 1,681 ⟶ 3,566:
println(@sprintf("%8d => ", i), @sprintf("%16s, ", class), a)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,712 ⟶ 3,597:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
data class Classification(val sequence: List<Long>, val aliquot: String)
Line 1,773 ⟶ 3,658:
val (seq, aliquot) = classifySequence(k)
println("$k: ${aliquot.padEnd(15)} $seq")
}</langsyntaxhighlight>
 
{{out}}
Line 1,823 ⟶ 3,708:
 
There are no sociable sequences.
<syntaxhighlight lang="lb">
<lang lb>
print "ROSETTA CODE - Aliquot sequence classifications"
[Start]
Line 1,868 ⟶ 3,753:
next
end function
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,937 ⟶ 3,822:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">seq[n_] :=
NestList[If[# == 0, 0,
DivisorSum[#, # &, Function[div, div != #]]] &, n, 16];
Line 1,955 ⟶ 3,840:
Print[{#, class[seq[#]], notate[seq[#]] /. {0} -> 0}] & /@ {1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909,
562, 1064, 1488, 15355717786080};</langsyntaxhighlight>
{{out}}
<pre>{1, Terminating, {1, 0}}
Line 1,981 ⟶ 3,866:
{1488, Non-terminating, {1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384, 1474608}}
{15355717786080, Non-terminating, {15355717786080, 44534663601120, 144940087464480, 471714103310688, 1130798979186912, 2688948041357088, 6050151708497568, 13613157922639968, 35513546724070632, 74727605255142168, 162658586225561832, 353930992506879768, 642678347124409032, 1125102611548462968, 1977286128289819992, 3415126495450394808, 7156435369823219592}}</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import std/[math, strformat, times]
from std/strutils import addSep
 
type
 
# Classification categories.
Category {.pure.} = enum
Unknown
Terminating = "terminating"
Perfect = "perfect"
Amicable = "amicable"
Sociable = "sociable"
Aspiring = "aspiring"
Cyclic = "cyclic"
NonTerminating = "non-terminating"
 
# Aliquot sequence.
AliquotSeq = seq[int64]
 
const Limit = 2^47 # Limit beyond which the category is considered to be "NonTerminating".
 
#---------------------------------------------------------------------------------------------------
 
proc sumProperDivisors(n: int64): int64 =
## Compute the sum of proper divisors.*
 
if n == 1: return 0
result = 1
for d in 2..sqrt(n.float).int:
if n mod d == 0:
inc result, d
if n div d != d:
result += n div d
 
#---------------------------------------------------------------------------------------------------
 
iterator aliquotSeq(n: int64): int64 =
## Yield the elements of the aliquot sequence of "n".
## Stopped if the current value is null or equal to "n".
 
var k = n
while true:
k = sumProperDivisors(k)
yield k
 
#---------------------------------------------------------------------------------------------------
 
proc `$`(a: AliquotSeq): string =
## Return the representation of an allquot sequence.
 
for n in a:
result.addSep(", ", 0)
result.addInt(n)
 
#---------------------------------------------------------------------------------------------------
 
proc classification(n: int64): tuple[cat: Category, values: AliquotSeq] =
## Return the category of the aliquot sequence of a number "n" and the sequence itself.
 
var count = 0 # Number of elements currently generated.
var prev = n # Previous element in the sequence.
result.cat = Unknown
for k in aliquotSeq(n):
inc count
if k == 0:
result.cat = Terminating
elif k == n:
result.cat = case count
of 1: Perfect
of 2: Amicable
else: Sociable
elif k > Limit or count > 16:
result.cat = NonTerminating
elif k == prev:
result.cat = Aspiring
elif k in result.values:
result.cat = Cyclic
prev = k
result.values.add(k)
if result.cat != Unknown:
break
 
#---------------------------------------------------------------------------------------------------
 
let t0 = getTime()
 
for n in 1..10:
let (cat, aseq) = classification(n)
echo fmt"{n:14}: {cat:<20} {aseq}"
 
echo ""
for n in [int64 11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488, 15355717786080]:
let (cat, aseq) = classification(n)
echo fmt"{n:14}: {cat:<20} {aseq}"
 
echo ""
echo fmt"Processed in {(getTime() - t0).inMilliseconds} ms."
</syntaxhighlight>
 
{{out}}
<pre>
1: terminating 0
2: terminating 1, 0
3: terminating 1, 0
4: terminating 3, 1, 0
5: terminating 1, 0
6: perfect 6
7: terminating 1, 0
8: terminating 7, 1, 0
9: terminating 4, 3, 1, 0
10: terminating 8, 7, 1, 0
 
11: terminating 1, 0
12: terminating 16, 15, 9, 4, 3, 1, 0
28: perfect 28
496: perfect 496
220: amicable 284, 220
1184: amicable 1210, 1184
12496: sociable 14288, 15472, 14536, 14264, 12496
1264460: sociable 1547860, 1727636, 1305184, 1264460
790: aspiring 650, 652, 496, 496
909: aspiring 417, 143, 25, 6, 6
562: cyclic 284, 220, 284
1064: cyclic 1336, 1184, 1210, 1184
1488: non-terminating 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384, 1474608, 2461648
15355717786080: non-terminating 44534663601120, 144940087464480
 
Processed in 105 ms.
</pre>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight lang="oforth">import: mapping
import: quicksort
import: math
Line 2,020 ⟶ 4,037:
]
"non-terminating"
;</langsyntaxhighlight>
 
{{out}}
Line 2,060 ⟶ 4,077:
=={{header|PARI/GP}}==
Define function aliquot(). Works with recent versions of PARI/GP >= 2.8:
<langsyntaxhighlight lang="parigp">aliquot(x) =
{
my (L = List(x), M = Map(Mat([x,1])), k, m = "non-term.", n = x);
Line 2,077 ⟶ 4,094:
);
printf("%16d: %10s, %s\n", x, m, Vec(L));
}</langsyntaxhighlight>
 
Output:
Line 2,106 ⟶ 4,123:
1488: non-term., [1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384]
15355717786080: non-term., [15355717786080, 44534663601120]</pre>
 
=={{header|Phix}}==
Translated from the Python example
<lang Phix>function aliquot(atom n)
sequence s = {n}
integer k
if n=0 then return {"terminating",{0}} end if
while length(s)<16
and n<140737488355328 do
n = sum(factors(n,-1))
k = find(n,s)
if k then
if k=1 then
if length(s)=1 then return {"perfect",s}
elsif length(s)=2 then return {"amicable",s}
end if return {"sociable",s}
elsif k=length(s) then return {"aspiring",s}
end if return {"cyclic",append(s,n)}
elsif n=0 then return {"terminating",s}
end if
s = append(s,n)
end while
return {"non-terminating",s}
end function
 
function flat_d(sequence s)
for i=1 to length(s) do s[i] = sprintf("%d",s[i]) end for
return join(s,",")
end function
 
constant n = tagset(12)&{28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080}
sequence class, dseq
for i=1 to length(n) do
{class, dseq} = aliquot(n[i])
printf(1,"%14d => %15s, {%s}\n",{n[i],class,flat_d(dseq)})
end for</lang>
{{out}}
<pre>
1 => terminating, {1}
2 => terminating, {2,1}
3 => terminating, {3,1}
4 => terminating, {4,3,1}
5 => terminating, {5,1}
6 => perfect, {6}
7 => terminating, {7,1}
8 => terminating, {8,7,1}
9 => terminating, {9,4,3,1}
10 => terminating, {10,8,7,1}
11 => terminating, {11,1}
12 => terminating, {12,16,15,9,4,3,1}
28 => perfect, {28}
496 => perfect, {496}
220 => amicable, {220,284}
1184 => amicable, {1184,1210}
12496 => sociable, {12496,14288,15472,14536,14264}
1264460 => sociable, {1264460,1547860,1727636,1305184}
790 => aspiring, {790,650,652,496}
909 => aspiring, {909,417,143,25,6}
562 => cyclic, {562,284,220,284}
1064 => cyclic, {1064,1336,1184,1210,1184}
1488 => non-terminating, {1488,2480,3472,4464,8432,9424,10416,21328,22320,55056,95728,96720,236592,459792,881392,882384}
15355717786080 => non-terminating, {15355717786080,44534663601120,144940087464480}
</pre>
 
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/divisor_sum/;
 
sub aliquot {
Line 2,207 ⟶ 4,161:
my($class, @seq) = aliquot($n);
printf "%14d %10s [@seq]\n", $n, $class;
}</langsyntaxhighlight>
{{out}}
<pre> 1 terminates [1 0]
Line 2,235 ⟶ 4,189:
15355717786080 non-term [15355717786080 44534663601120]</pre>
 
=={{header|Perl 6Phix}}==
Translated from the Python example
{{works with|rakudo|2018.10}}
<!--<syntaxhighlight lang="phix">-->
<lang perl6>sub propdivsum (\x) {
<span style="color: #008080;">function</span> <span style="color: #000000;">aliquot</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
my @l = x > 1;
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}</span>
(2 .. x.sqrt.floor).map: -> \d {
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span>
unless x % d { my \y = x div d; y == d ?? @l.push: d !! @l.append: d,y }
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"terminating"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
}
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">16</span>
sum @l;
<span style="color: #008080;">and</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">140737488355328</span> <span style="color: #008080;">do</span>
}
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"perfect"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"amicable"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"sociable"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"aspiring"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"cyclic"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)}</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"terminating"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"non-terminating"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">12</span><span style="color: #0000FF;">)&{</span><span style="color: #000000;">28</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">496</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">220</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1184</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">12496</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1264460</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">790</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">909</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">562</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1064</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1488</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15355717786080</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">string</span> <span style="color: #000000;">classification</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">dseq</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">aliquot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #000000;">dseq</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: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">,{{</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">},</span><span style="color: #000000;">dseq</span><span style="color: #0000FF;">}),</span><span style="color: #008000;">","</span><span style="color: #0000FF;">)</span>
<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;">"%14d =&gt; %15s, {%s}\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">classification</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dseq</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
1 => terminating, {1}
2 => terminating, {2,1}
3 => terminating, {3,1}
4 => terminating, {4,3,1}
5 => terminating, {5,1}
6 => perfect, {6}
7 => terminating, {7,1}
8 => terminating, {8,7,1}
9 => terminating, {9,4,3,1}
10 => terminating, {10,8,7,1}
11 => terminating, {11,1}
12 => terminating, {12,16,15,9,4,3,1}
28 => perfect, {28}
496 => perfect, {496}
220 => amicable, {220,284}
1184 => amicable, {1184,1210}
12496 => sociable, {12496,14288,15472,14536,14264}
1264460 => sociable, {1264460,1547860,1727636,1305184}
790 => aspiring, {790,650,652,496}
909 => aspiring, {909,417,143,25,6}
562 => cyclic, {562,284,220,284}
1064 => cyclic, {1064,1336,1184,1210,1184}
1488 => non-terminating, {1488,2480,3472,4464,8432,9424,10416,21328,22320,55056,95728,96720,236592,459792,881392,882384}
15355717786080 => non-terminating, {15355717786080,44534663601120,144940087464480}
</pre>
 
=={{header|Picat}}==
multi quality (0,1) { 'perfect ' }
{{trans|C++}}
multi quality (0,2) { 'amicable' }
<syntaxhighlight lang="picat">divisor_sum(N) = R =>
multi quality (0,$n) { "sociable-$n" }
Total = 1,
multi quality ($,1) { 'aspiring' }
Power = 2,
multi quality ($,$n) { "cyclic-$n" }
% Deal with powers of 2 first
while (N mod 2 == 0)
Total := Total + Power,
Power := Power*2,
N := N div 2
end,
% Odd prime factors up to the square root
P = 3,
while (P*P =< N)
Sum = 1,
Power1 = P,
while (N mod P == 0)
Sum := Sum + Power1,
Power1 := Power1*P,
N := N div P
end,
Total := Total * Sum,
P := P+2
end,
% If n > 1 then it's prime
if N > 1 then
Total := Total*(N + 1)
end,
R = Total.
 
% See https://en.wikipedia.org/wiki/Aliquot_sequence
sub aliquotidian ($x) {
aliquot_sequence(N,Limit,Seq,Class) =>
my %seen;
aliquot_sequence(N,Limit,[N],Seq,Class).
my @seq = $x, &propdivsum ... *;
for 0..16 -> $to {
aliquot_sequence(_,0,_,Seq,Class) => Seq = [], Class = 'non-terminating'.
my $this = @seq[$to] or return "$x\tterminating\t[@seq[^$to]]";
aliquot_sequence(_,_,[0|_],Seq,Class) => Seq = [0], Class = terminating.
last if $this > 140737488355328;
aliquot_sequence(N,_,[N,N|_],Seq,Class) => Seq = [], Class = perfect.
if %seen{$this}:exists {
aliquot_sequence(N,_,[N,_,N|_],Seq,Class) => Seq = [N], Class = amicable.
my $from = %seen{$this};
aliquot_sequence(N,_,[N|S],Seq,Class), membchk(N,S) =>
return "$x\t&quality($from, $to-$from)\t[@seq[^$to]]";
Seq = [N], Class }= sociable.
aliquot_sequence(_,_,[Term,Term|_],Seq,Class) => Seq = [], Class = aspiring.
%seen{$this} = $to;
aliquot_sequence(_,_,[Term|S],Seq,Class), membchk(Term,S) =>
}
Seq = [Term], Class = cyclic.
"$x non-terminating\t[{@seq}]";
aliquot_sequence(N,Limit,[Term|S],Seq,Class) =>
}
Seq = [Term|Rest],
Sum = divisor_sum(Term),
Term1 is Sum - Term,
aliquot_sequence(N,Limit-1,[Term1,Term|S],Rest,Class).
 
main =>
aliquotidian($_).say for flat
foreach (N in [11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488,15355717786080,153557177860800])
1..10,
aliquot_sequence(N,16,Seq,Class),
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790 printf("%w: %w, 909sequence: %w ", 562N, 1064Class, 1488Seq[1]),
foreach (I in 2..len(Seq), break(Seq[I] == Seq[I-1]))
15355717786080;</lang>
printf("%w ", Seq[I])
end,
nl
end.
</syntaxhighlight>
{{out}}
<pre>1 terminating [1]
2 11: terminating [2, sequence: 11 1] 0
3 12: terminating [, sequence: 12 16 15 9 4 3 1] 0
28: perfect, sequence: 28
4 terminating [4 3 1]
496: perfect, sequence: 496
5 terminating [5 1]
220: amicable, sequence: 220 284 220
6 perfect [6]
1184: amicable, sequence: 1184 1210 1184
7 terminating [7 1]
12496: sociable, sequence: 12496 14288 15472 14536 14264 12496
8 terminating [8 7 1]
1264460: sociable, sequence: 1264460 1547860 1727636 1305184 1264460
9 terminating [9 4 3 1]
790: aspiring, sequence: 790 650 652 496
10 terminating [10 8 7 1]
909: aspiring, sequence: 909 417 143 25 6
11 terminating [11 1]
562: cyclic, sequence: 562 284 220 284
12 terminating [12 16 15 9 4 3 1]
1064: cyclic, sequence: 1064 1336 1184 1210 1184
28 perfect [28]
1488: non-terminating, sequence: 1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384
496 perfect [496]
15355717786080: non-terminating, sequence: 15355717786080 44534663601120 144940087464480 471714103310688 1130798979186912 2688948041357088 6050151708497568 13613157922639968 35513546724070632 74727605255142168 162658586225561832 353930992506879768 642678347124409032 1125102611548462968 1977286128289819992 3415126495450394808
220 amicable [220 284]
153557177860800: non-terminating, sequence: 153557177860800 470221741508000 685337334283120 908681172226160 1276860840159280 1867115442105104 1751034184622896 1643629718341256 1441432897905784 1647351883321016 1557892692704584 1363939602434936 1194001297910344 1597170567336056 1405725265675144 1230017019320456
1184 amicable [1184 1210]
12496 sociable-5 [12496 14288 15472 14536 14264]
1264460 sociable-4 [1264460 1547860 1727636 1305184]
790 aspiring [790 650 652 496]
909 aspiring [909 417 143 25 6]
562 cyclic-2 [562 284 220]
1064 cyclic-2 [1064 1336 1184 1210]
1488 non-terminating [1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608 ...]
15355717786080 non-terminating [15355717786080 44534663601120 144940087464480 ...]
</pre>
 
Line 2,309 ⟶ 4,338:
{{works with|PowerShell|4.0}}<br/>
<b>Simple</b>
<langsyntaxhighlight lang="powershell">function Get-NextAliquot ( [int]$X )
{
If ( $X -gt 1 )
Line 2,342 ⟶ 4,371:
(1..10).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }
( 11, 12, 28, 496, 220, 1184, 790, 909, 562, 1064, 1488 ).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }</langsyntaxhighlight>
<b>Optimized</b>
<langsyntaxhighlight lang="powershell">function Get-NextAliquot ( [int]$X )
{
If ( $X -gt 1 )
Line 2,406 ⟶ 4,435:
(1..10).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }
( 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 ).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }</langsyntaxhighlight>
{{out}}
<pre>1 is terminating
Line 2,433 ⟶ 4,462:
 
===Version 3.0===
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-Aliquot
{
Line 2,524 ⟶ 4,553:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
$oneToTen = 1..10 | Get-Aliquot
$selected = 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 | Get-Aliquot
Line 2,531 ⟶ 4,560:
$numbers = $oneToTen, $selected
$numbers
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,559 ⟶ 4,588:
1064 cyclic
1488 non-terminating and non-repeating through N = 16
</pre>
 
=={{header|Prolog}}==
{{trans|C++}}
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">% See https://en.wikipedia.org/wiki/Divisor_function
divisor_sum(N, Total):-
divisor_sum_prime(N, 2, 2, Total1, 1, N1),
divisor_sum(N1, 3, Total, Total1).
 
divisor_sum(1, _, Total, Total):-
!.
divisor_sum(N, Prime, Total, Running_total):-
Prime * Prime =< N,
!,
divisor_sum_prime(N, Prime, Prime, P, 1, M),
Next_prime is Prime + 2,
Running_total1 is P * Running_total,
divisor_sum(M, Next_prime, Total, Running_total1).
divisor_sum(N, _, Total, Running_total):-
Total is (N + 1) * Running_total.
 
divisor_sum_prime(N, Prime, Power, Total, Running_total, M):-
0 is N mod Prime,
!,
Running_total1 is Running_total + Power,
Power1 is Power * Prime,
N1 is N // Prime,
divisor_sum_prime(N1, Prime, Power1, Total, Running_total1, M).
divisor_sum_prime(N, _, _, Total, Total, N).
 
% See https://en.wikipedia.org/wiki/Aliquot_sequence
aliquot_sequence(N, Limit, Sequence, Class):-
aliquot_sequence(N, Limit, [N], Sequence, Class).
 
aliquot_sequence(_, 0, _, [], 'non-terminating'):-!.
aliquot_sequence(_, _, [0|_], [0], terminating):-!.
aliquot_sequence(N, _, [N, N|_], [], perfect):-!.
aliquot_sequence(N, _, [N, _, N|_], [N], amicable):-!.
aliquot_sequence(N, _, [N|S], [N], sociable):-
memberchk(N, S),
!.
aliquot_sequence(_, _, [Term, Term|_], [], aspiring):-!.
aliquot_sequence(_, _, [Term|S], [Term], cyclic):-
memberchk(Term, S),
!.
aliquot_sequence(N, Limit, [Term|S], [Term|Rest], Class):-
divisor_sum(Term, Sum),
Term1 is Sum - Term,
L1 is Limit - 1,
aliquot_sequence(N, L1, [Term1, Term|S], Rest, Class).
 
write_aliquot_sequence(N, Sequence, Class):-
writef('%w: %w, sequence:', [N, Class]),
write_aliquot_sequence(Sequence).
 
write_aliquot_sequence([]):-
nl,
!.
write_aliquot_sequence([Term|Rest]):-
writef(' %w', [Term]),
write_aliquot_sequence(Rest).
 
main:-
between(1, 10, N),
aliquot_sequence(N, 16, Sequence, Class),
write_aliquot_sequence(N, Sequence, Class),
fail.
main:-
member(N, [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]),
aliquot_sequence(N, 16, Sequence, Class),
write_aliquot_sequence(N, Sequence, Class),
fail.
main.</syntaxhighlight>
 
{{out}}
<pre>
1: terminating, sequence: 1 0
2: terminating, sequence: 2 1 0
3: terminating, sequence: 3 1 0
4: terminating, sequence: 4 3 1 0
5: terminating, sequence: 5 1 0
6: perfect, sequence: 6
7: terminating, sequence: 7 1 0
8: terminating, sequence: 8 7 1 0
9: terminating, sequence: 9 4 3 1 0
10: terminating, sequence: 10 8 7 1 0
11: terminating, sequence: 11 1 0
12: terminating, sequence: 12 16 15 9 4 3 1 0
28: perfect, sequence: 28
496: perfect, sequence: 496
220: amicable, sequence: 220 284 220
1184: amicable, sequence: 1184 1210 1184
12496: sociable, sequence: 12496 14288 15472 14536 14264 12496
1264460: sociable, sequence: 1264460 1547860 1727636 1305184 1264460
790: aspiring, sequence: 790 650 652 496
909: aspiring, sequence: 909 417 143 25 6
562: cyclic, sequence: 562 284 220 284
1064: cyclic, sequence: 1064 1336 1184 1210 1184
1488: non-terminating, sequence: 1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384
</pre>
 
Line 2,564 ⟶ 4,693:
Importing [[Proper_divisors#Python:_From_prime_factors|Proper divisors from prime factors]]:
 
<langsyntaxhighlight lang="python">from proper_divisors import proper_divs
from functools import lru_cache
 
Line 2,604 ⟶ 4,733:
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))</langsyntaxhighlight>
 
{{out}}
Line 2,632 ⟶ 4,761:
non-terminating: [1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384, 1474608]
non-terminating: [15355717786080, 44534663601120, 144940087464480]</pre>
 
=={{header|QBasic}}==
{{works with|QBasic|1.1}}
{{trans|Liberty BASIC}}
<syntaxhighlight lang="qbasic">DECLARE FUNCTION PDtotal! (n!)
DECLARE SUB PrintAliquotClassifier (K!)
CLS
CONST limite = 10000000
 
DIM nums(22)
DATA 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496
DATA 220, 1184, 12496, 790, 909, 562, 1064, 1488
 
FOR n = 1 TO UBOUND(nums)
READ nums(n)
PRINT "Number"; nums(n); " :";
PrintAliquotClassifier (nums(n))
NEXT n
 
PRINT "Program normal end."
END
 
FUNCTION PDtotal (n)
total = 0
FOR y = 2 TO n
IF (n MOD y) = 0 THEN total = total + (n / y)
NEXT y
PDtotal = total
END FUNCTION
 
SUB PrintAliquotClassifier (K)
longit = 52: n = K: clase = 0: priorn = 0: inc = 0
DIM Aseq(longit)
FOR element = 2 TO longit
Aseq(element) = PDtotal(n)
PRINT Aseq(element); " ";
COLOR 3
SELECT CASE Aseq(element)
CASE 0
PRINT " Terminating": clase = 1: EXIT FOR
CASE K AND element = 2
PRINT " Perfect": clase = 2: EXIT FOR
CASE K AND element = 3
PRINT " Amicable": clase = 3: EXIT FOR
CASE K AND element > 3
PRINT " Sociable": clase = 4: EXIT FOR
CASE Aseq(element) <> K AND Aseq(element - 1) = Aseq(element)
PRINT " Aspiring": clase = 5: EXIT FOR
CASE Aseq(element) <> K AND Aseq(element - 2) = Aseq(element)
PRINT " Cyclic": clase = 6: EXIT FOR
END SELECT
COLOR 7
n = Aseq(element)
IF n > priorn THEN priorn = n: inc = inc + 1 ELSE inc = 0: priorn = 0
IF inc = 11 OR n > limite THEN EXIT FOR
NEXT element
IF clase = 0 THEN COLOR 12: PRINT " non-terminating"
COLOR 7
END SUB</syntaxhighlight>
{{out}}
<pre>Number 1 : 0 Terminating
Number 2 : 1 0 Terminating
Number 3 : 1 0 Terminating
Number 4 : 3 1 0 Terminating
Number 5 : 1 0 Terminating
Number 6 : 6 Perfect
Number 7 : 1 0 Terminating
Number 8 : 7 1 0 Terminating
Number 9 : 4 3 1 0 Terminating
Number 10 : 8 7 1 0 Terminating
Number 11 : 1 0 Terminating
Number 12 : 16 15 9 4 3 1 0 Terminating
Number 28 : 28 Perfect
Number 496 : 496 Perfect
Number 220 : 284 220 Amicable
Number 1184 : 1210 1184 Amicable
Number 12496 : 14288 15472 14536 14264 12496 Sociable
Number 790 : 650 652 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 non-terminating
Number 909 : 417 143 25 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 non-terminating
Number 562 : 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 non-terminating
Number 1064 : 1336 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 non-terminating
Number 1488 : 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 non-terminating
Program normal end.</pre>
 
 
=={{header|Racket}}==
Line 2,637 ⟶ 4,851:
'''fold-divisors''' is used from [[Proper_divisors#Racket]], but for the truly big numbers, we use divisors from math/number-theory.
 
<langsyntaxhighlight lang="racket">#lang racket
(require "proper-divisors.rkt" math/number-theory)
 
Line 2,689 ⟶ 4,903:
 
(for ((i (in-list '(11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080))))
(report-aliquot-sequence-class i))</langsyntaxhighlight>
 
{{out}}
Line 2,716 ⟶ 4,930:
1488: non-terminating long sequence (1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608)
15355717786080: non-terminating big number (15355717786080 44534663601120 144940087464480)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2018.10}}
<syntaxhighlight lang="raku" line>sub propdivsum (\x) {
my @l = x > 1;
(2 .. x.sqrt.floor).map: -> \d {
unless x % d { my \y = x div d; y == d ?? @l.push: d !! @l.append: d,y }
}
sum @l;
}
 
multi quality (0,1) { 'perfect ' }
multi quality (0,2) { 'amicable' }
multi quality (0,$n) { "sociable-$n" }
multi quality ($,1) { 'aspiring' }
multi quality ($,$n) { "cyclic-$n" }
 
sub aliquotidian ($x) {
my %seen;
my @seq = $x, &propdivsum ... *;
for 0..16 -> $to {
my $this = @seq[$to] or return "$x\tterminating\t[@seq[^$to]]";
last if $this > 140737488355328;
if %seen{$this}:exists {
my $from = %seen{$this};
return "$x\t&quality($from, $to-$from)\t[@seq[^$to]]";
}
%seen{$this} = $to;
}
"$x non-terminating\t[{@seq}]";
}
 
aliquotidian($_).say for flat
1..10,
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488,
15355717786080;</syntaxhighlight>
{{out}}
<pre>1 terminating [1]
2 terminating [2 1]
3 terminating [3 1]
4 terminating [4 3 1]
5 terminating [5 1]
6 perfect [6]
7 terminating [7 1]
8 terminating [8 7 1]
9 terminating [9 4 3 1]
10 terminating [10 8 7 1]
11 terminating [11 1]
12 terminating [12 16 15 9 4 3 1]
28 perfect [28]
496 perfect [496]
220 amicable [220 284]
1184 amicable [1184 1210]
12496 sociable-5 [12496 14288 15472 14536 14264]
1264460 sociable-4 [1264460 1547860 1727636 1305184]
790 aspiring [790 650 652 496]
909 aspiring [909 417 143 25 6]
562 cyclic-2 [562 284 220]
1064 cyclic-2 [1064 1336 1184 1210]
1488 non-terminating [1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608 ...]
15355717786080 non-terminating [15355717786080 44534663601120 144940087464480 ...]
</pre>
 
Line 2,725 ⟶ 5,003:
Two versions of &nbsp; ''classifications'' &nbsp; of &nbsp; ''non-terminating'' &nbsp; are used:
::* &nbsp; (lowercase) &nbsp; '''non-terminating''' &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ─── &nbsp; due to more than sixteen cyclic numbers
::* &nbsp; (uppercase) &nbsp; '''NON-TERMINATING''' &nbsp; &nbsp; ─── &nbsp; due to a cyclic number that is larger than &nbsp; <big>2<sup>47</sup></big>
 
Both of the above limitations are imposed by this Rosetta Code task's restriction requirements: &nbsp; ''For the purposes of this task, ···''.
<langsyntaxhighlight lang="rexx">/*REXX program classifies various positive integers for For types of aliquot sequences. */
parseParse argArg low high L LL /*obtain optional arguments from the CL*/
high=word(high low 10,1); low=word(low 1,1) /*obtain the LOW and HIGH (range). */
low=word(low 1,1) /*obtain the LOW and HIGH (range). */
if L='' then L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080
If LL='' Then
numeric digits 100 /*be able to compute the number: BIG */
LL=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080
big= 2**47; NTlimit= 16 + 1 /*limits for a non─terminating sequence*/
numericNumeric Digits 20 digits max(9, 1 + length(big) ) /*be able toTo handlecompute bigthe numbersnumber: for //BIG */
big=2**47
#.=.; #.0=0; #.1=0 /*#. are the proper divisor sums. */
sayNTlimit=16+1 center('numbers from ' low " to " high, 79, "═") /*limit for a non-terminating sequence */
Numeric Digits max(9,length(big)) /*be able To handle big numbers For // */
do n=low to high; call classify n /*call a subroutine to classify number.*/
digs=digits() end /*n*/ /*used [↑] process aFor rangealign ofnumbers integers.For the output*/
dsum.=.
say
dsum.0=0
say center('first numbers for each classification', 79, "═")
classdsum.1=0 /* [↓]dsum. are ensurethe oneproper numberdivisor ofsums. each class*/
Say 'Numbers from ' low ' ---> ' high ' (inclusive):'
do q=1 until class.sociable\==0 /*the only one that has to be counted. */
Do n=low To high call classify -q /* process specified range /*minus (-) sign indicates don't tell. */
Call classify n _=what; upper _; class._= class._ +1 /*bump countercall forsubroutine thisTo classclassify sequencenumber. */
End
if class._==1 then say right(q, digits()) 'is' center(what, 15) $
Say
end /*q*/ /* [↑] only display the 1st occurrence*/
Say 'First numbers for each classification:'
say /* [↑] process until all classes found*/
class.=0 /* [?] ensure one number of each class*/
say center('classifications for specific numbers', 79, "═")
Do do iq=1 Until for words(L) class.sociable\==0 /*L:the only one isthat ahas listTo ofbe counted. "special numbers".*/
Call classify -q call classify word(L, i) /*callminus a(-) subroutinesign toindicates classifydon't numbertell. */
end /*i*/ _=translate(what) /*obtain [↑]the class processand auppercase list of integersit. */
exit class._=class._+1 /*stickbump acounter forkFor inthis it,class we're all donesequence. */
If class._==1 Then /*first number of this class */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Call out q,what,dd
classify: parse arg a 1 aa; a=abs(a) /*obtain number that's to be classified*/
End
if #.a\==. then s=#.a /*Was this number been summed before?*/
Say else s=sigma(a) /*No, then[?] classifyprocess numberUntil theall hardclasses wayfound*/
Say 'Classifications for specific numbers:'
#.a=s; $=s /*define sum of the proper divisors. */
Do i=1 To words(LL) what= 'terminating' /*assume thisprocess a kindlist of classification."special numbers" */
Call classify c.=0; c.s=1 word(LL,i) /*clearcall allsubroutine cyclicTo sequences;classify number. set 1st.*/
End
if $==a then what= 'perfect' /*check for a "perfect" number. */
Exit else do t=1 while s\==0 /*loop until sum isn't 0 or /*stick >a bigfork in it,we're all done. */
out:
m=s /*obtain the last number in sequence. */
Parse arg number,class,dd
if #.m==. then s=sigma(m) /*Not defined? Then sum proper divisors*/
dd.=''
else s=#.m /*use the previously found integer. */
Do di=1 By 1 While length(dd)>50
if m==s & m\==0 then do; what= 'aspiring' ; leave; end
do dj=50 To 10 By -1
parse var $ . word2 . /*obtain the 2nd number in sequence. */
If substr(dd,dj,1)=' ' Then Leave
if word2==a then do; what= 'amicable' ; leave; end
End
$=$ s /*append a sum to the integer sequence.*/
dd.di=left(dd,dj)
if s==a & t>3 then do; what= 'sociable' ; leave; end
dd=substr(dd,dj+1)
if c.s & m\==0 then do; what= 'cyclic' ; leave; end
End
c.s=1 /*assign another possible cyclic number*/
dd.di=dd
/* [↓] Rosetta Code task's limit: >16 */
Say right(number,digs)':' center(class,digs) dd.1||conti(1)
if t>NTlimit then do; what= 'non-terminating'; leave; end
Do di=2 By 1 While dd.di>''
if s>big then do; what= 'NON-TERMINATING'; leave; end
Say copies(' ',33)dd.di||conti(di)
end /*t*/ /* [↑] only permit within reason. */
End
if aa>0 then say right(a, digits() ) 'is' center(what, 15) $
Return
return /* [↑] only display if AA is positive*/
conti:
/*──────────────────────────────────────────────────────────────────────────────────────*/
Parse arg this
sigma: procedure expose #. !.; parse arg x; if x<2 then return 0; odd=x//2
next=this+1
s=1 /* [↓] use EVEN or ODD integers. ___*/
If dd.next>'' Then Return '...'
do j=2+odd by 1+odd while j*j<x /*divide by all the integers up to √ X */
Else Return ''
if x//j==0 then s=s + j + x%j /*add the two divisors to the sum. */
/*---------------------------------------------------------------------------------*/
end /*j*/ /* [↓] adjust for square. ___*/
classify:
if j*j==x then s=s + j /*Was X a square? If so, add √ X */
Parse Arg a 1 aa
#.x=s /*define division sum for argument X.*/
return sa=abs(a) /*returnobtain number that's to be " " " " " classified*/</lang>
If dsum.a\==. Then
s=dsum.a /*Was this number been summed before?*/
Else
s=dsum(a) /*No,Then classify number the hard way */
dsum.a=s /*define sum of the proper divisors. */
dd=s /*define the start of integer sequence.*/
what='terminating' /*assume this kind of classification. */
c.=0 /*clear all cyclic sequences (to zero).*/
c.s=1 /*set the first cyclic sequence. */
If dd==a Then
what='perfect' /*check For a "perfect" number. */
Else Do t=1 By 1 While s>0 /*loop Until sum isn't 0 or > big.*/
m=s /*obtain the last number in sequence. */
If dsum.m==. Then /*Not defined? */
s=dsum(m) /* compute sum pro of per divisors */
Else
s=dsum.m /*use the previously found integer. */
If m==s Then
If m>=0 Then Do
what='aspiring'
Leave
End
If word(dd,2)=a Then Do
what='amicable'
Leave
End
dd=dd s /*append a sum To the integer sequence.*/
If s==a Then
If t>3 Then Do
what='sociable'
Leave
End
If c.s Then
If m>0 Then Do
what='cyclic'
Leave
End
c.s=1 /*assign another possible cyclic number*/
/* [?] Rosetta Code task's limit: >16 */
If t>NTlimit Then Do
what='non-terminating'
Leave
End
If s>big Then Do
what='NON-TERMINATING'
Leave
End
End
If aa>0 Then /* display only if AA is positive */
Call out a,what,dd
Return
/*---------------------------------------------------------------------------------*/
dsum: Procedure Expose dsum. /* compute the sum of proper divisors */
Parse Arg x
If x<2 Then
Return 0
odd=x//2
s=1 /* use EVEN or ODD integers. */
Do j=2+odd by 1+odd While j*j<x /* divide by all the integers ) */
/* up to but excluding sqrt(x) */
If x//j==0 Then /* j is a divisor, so is x%j */
s=s+j+x%j /*add the two divisors To the sum. */
End
If j*j==x Then /* if x is a square */
s=s+j /* add sqrt(X) */
dsum.x=s /* memoize proper divisor sum of X */
Return s /* return the proper divisor sum */
</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>Numbers from 1 ---> 10 (inclusive):
<pre>
1: terminating 0
════════════════════════════numbers from 1 to 10════════════════════════════
1 is2: terminating 1 0
2 is3: terminating 1 0
3 is4: terminating 3 1 0
4 is5: terminating 3 1 0
56: is terminating perfect 1 0 6
67: is terminating perfect1 60
7 is8: terminating 7 1 0
8 is9: terminating 74 3 1 0
9 is10: terminating 48 37 1 0
 
10 is terminating 8 7 1 0
First numbers for each classification:
1: terminating 0
6: perfect 6
25: aspiring 6
138: non-terminating 150 222 234 312 528 960 2088 3762 5598 6570 10746 ...
13254 13830 19434 20886 21606 25098 26742 26754
220: amicable 284 220
562: cyclic 284 220 284
12496: sociable 14288 15472 14536 14264 12496
 
Classifications for specific numbers:
═════════════════════first numbers for each classification═════════════════════
11: 1 is terminating terminating 1 0
12: 6 is terminating 16 perfect15 9 4 3 1 60
2528: is aspiringperfect 628
496: perfect 496
138 is non-terminating 150 222 234 312 528 960 2088 3762 5598 6570 10746 13254 13830 19434 20886 21606 25098 26742 26754
220 is: amicable 284 220
1184: 562 is amicable cyclic 1210 284 220 2841184
12496 is: sociable 14288 15472 14536 14264 12496
1264460: cyclic 1547860 1727636 1305184 1264460 1547860
790: aspiring 650 652 496
909: aspiring 417 143 25 6
562: cyclic 284 220 284
1064: cyclic 1336 1184 1210 1184
1488: non-terminating 2480 3472 4464 8432 9424 10416 21328 22320 55056 ...
95728 96720 236592 459792 881392 882384 1474608 ...
2461648 3172912 3173904
15355717786080: NON-TERMINATING 44534663601120 144940087464480
 
═════════════════════classifications for specific numbers══════════════════════
11 is terminating 1 0
12 is terminating 16 15 9 4 3 1 0
28 is perfect 28
496 is perfect 496
220 is amicable 284 220
1184 is amicable 1210 1184
12496 is sociable 14288 15472 14536 14264 12496
1264460 is cyclic 1547860 1727636 1305184 1264460 1547860
790 is aspiring 650 652 496
909 is aspiring 417 143 25 6
562 is cyclic 284 220 284
1064 is cyclic 1336 1184 1210 1184
1488 is non-terminating 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608 2461648 3172912 3173904
15355717786080 is NON-TERMINATING 44534663601120 144940087464480
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Aliquot sequence classnifications
 
Line 2,907 ⟶ 5,256:
next
return pdtotal
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,972 ⟶ 5,321:
Enter an integer:
Program complete.
</pre>
 
=={{header|RPL}}==
{{works with|HP|49}}
≪ DIVIS DUP SIZE
'''IF''' DUP 2 ≤ '''THEN''' 1 - NIP '''ELSE''' 1 SWAP 1 - SUB ∑LIST '''END'''
R→I
≫ ≫ ‘<span style="color:blue">∑PFAC</span>’ STO
≪ 16 2 47 ^ → smax vmax
≪ { } OVER +
'''DO'''
SWAP <span style="color:blue">∑PFAC</span> SWAP OVER +
'''UNTIL''' OVER NOT LASTARG vmax ≥ OR OVER SIZE smax ≥ OR
'''END''' NIP
≫ ≫ ‘<span style="color:blue">ALIQT</span>’ STO
≪ <span style="color:blue">ALIQT</span> DUP HEAD → seq k
≪ '''CASE'''
seq 0 POS '''THEN''' "terminating" '''END'''
seq 2 GET k == '''THEN''' "perfect" '''END'''
seq 3 GET k == '''THEN''' "amicable" '''END'''
seq 4 OVER SIZE SUB k POS '''THEN''' "sociable" '''END'''
seq ΔLIST 0 POS '''THEN''' "aspiring" '''END'''
seq SORT ΔLIST 0 POS '''THEN''' "cyclic" '''END'''
"non-terminating"
'''END'''
≫ ≫ ‘<span style="color:blue">ALIQLASS</span>’ STO
 
≪ n <span style="color:blue">ALIQLASS</span> ≫ 'n' 1 10 1 SEQ
{11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080} 1 ≪ <span style="color:blue">ALIQLASS</span> ≫ DOLIST
{{out}}
<pre>
2: { "terminating" "terminating" "terminating" "terminating" "terminating" "terminating" "perfect" "terminating" "terminating" "terminating" }
1: { "terminating" "terminating" "perfect" "perfect" "amicable" "amicable" "sociable" "sociable" "aspiring" "aspiring" "cyclic" "cyclic" "non-terminating" "non-terminating" }
</pre>
 
Line 2,978 ⟶ 5,363:
{{trans|Python}}
 
<langsyntaxhighlight lang="ruby">def aliquot(n, maxlen=16, maxterm=2**47)
return "terminating", [0] if n == 0
s = []
Line 3,006 ⟶ 5,391:
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]
puts "%20s: %p" % aliquot(n)
end</langsyntaxhighlight>
 
{{out}}
Line 3,038 ⟶ 5,423:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">#[derive(Debug)]
enum AliquotType { Terminating, Perfect, Amicable, Sociable, Aspiring, Cyclic, NonTerminating }
 
Line 3,082 ⟶ 5,467:
println!("{} {:?}", num, classify_aliquot(*num));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,112 ⟶ 5,497:
=={{header|Scala}}==
Put [[proper_divisors#Scala]] the full /Proper divisors for big (long) numbers/ section to the beginning:
<langsyntaxhighlight Scalalang="scala">def createAliquotSeq(n: Long, step: Int, list: List[Long]): (String, List[Long]) = {
val sum = properDivisors(n).sum
if (sum == 0) ("terminate", list ::: List(sum))
Line 3,131 ⟶ 5,516:
val result = numbers.map(i => createAliquotSeq(i, 0, List(i)))
 
result foreach { v => println(f"${v._2.head}%14d ${v._1}%10s [${v._2 mkString " "}]" ) }</langsyntaxhighlight>
 
{{out}}
Line 3,158 ⟶ 5,543:
1488 non-term [1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608]
15355717786080 non-term [15355717786080 44534663601120]</pre>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
 
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
 
return sorted ? res.sorted() : Array(res)
}
}
 
struct SeqClass: CustomStringConvertible {
var seq: [Int]
var desc: String
 
var description: String {
return "\(desc): \(seq)"
}
}
 
func classifySequence(k: Int, threshold: Int = 1 << 47) -> SeqClass {
var last = k
var seq = [k]
 
while true {
last = last.factors().dropLast().reduce(0, +)
seq.append(last)
 
let n = seq.count
 
if last == 0 {
return SeqClass(seq: seq, desc: "Terminating")
} else if n == 2 && last == k {
return SeqClass(seq: seq, desc: "Perfect")
} else if n == 3 && last == k {
return SeqClass(seq: seq, desc: "Amicable")
} else if n >= 4 && last == k {
return SeqClass(seq: seq, desc: "Sociable[\(n - 1)]")
} else if last == seq[n - 2] {
return SeqClass(seq: seq, desc: "Aspiring")
} else if seq.dropFirst().dropLast(2).contains(last) {
return SeqClass(seq: seq, desc: "Cyclic[\(n - 1 - seq.firstIndex(of: last)!)]")
} else if n == 16 || last > threshold {
return SeqClass(seq: seq, desc: "Non-terminating")
}
}
 
fatalError()
}
 
for i in 1...10 {
print("\(i): \(classifySequence(k: i))")
}
 
print()
 
for i in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] {
print("\(i): \(classifySequence(k: i))")
}
 
print()
 
print("\(15355717786080): \(classifySequence(k: 15355717786080))")</syntaxhighlight>
 
{{out}}
 
<pre>1: Terminating: [1, 0]
2: Terminating: [2, 1, 0]
3: Terminating: [3, 1, 0]
4: Terminating: [4, 3, 1, 0]
5: Terminating: [5, 1, 0]
6: Perfect: [6, 6]
7: Terminating: [7, 1, 0]
8: Terminating: [8, 7, 1, 0]
9: Terminating: [9, 4, 3, 1, 0]
10: Terminating: [10, 8, 7, 1, 0]
 
11: Terminating: [11, 1, 0]
12: Terminating: [12, 16, 15, 9, 4, 3, 1, 0]
28: Perfect: [28, 28]
496: Perfect: [496, 496]
220: Amicable: [220, 284, 220]
1184: Amicable: [1184, 1210, 1184]
12496: Sociable[5]: [12496, 14288, 15472, 14536, 14264, 12496]
1264460: Sociable[4]: [1264460, 1547860, 1727636, 1305184, 1264460]
790: Aspiring: [790, 650, 652, 496, 496]
909: Aspiring: [909, 417, 143, 25, 6, 6]
562: Cyclic[2]: [562, 284, 220, 284]
1064: Cyclic[2]: [1064, 1336, 1184, 1210, 1184]
1488: Non-terminating: [1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384]
 
15355717786080: Non-terminating: [15355717786080, 44534663601120, 144940087464480]</pre>
 
=={{header|Tcl}}==
Line 3,163 ⟶ 5,647:
This solution creates an iterator from a coroutine to generate aliquot sequences. al_classify uses a "RESULT" exception to achieve some unusual control flow.
 
<langsyntaxhighlight Tcllang="tcl">proc ProperDivisors {n} {
if {$n == 1} {return 0}
set divs 1
Line 3,235 ⟶ 5,719:
puts [time {
puts [format "%8d -> %-16s : %s" $i {*}[al_classify $i]]
}]</langsyntaxhighlight>
 
{{out}}
Line 3,269 ⟶ 5,753:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Private Type Aliquot
Line 3,335 ⟶ 5,819:
SumPDiv = t
End Function
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,362 ⟶ 5,846:
Aliquot seq of 1488 : non-terminating 1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import math
const threshold = u64(1) << 47
fn index_of(s []u64, search u64) int {
for i, e in s {
if e == search {
return i
}
}
return -1
}
fn contains(s []u64, search u64) bool {
return index_of(s, search) > -1
}
fn max_of(i1 int, i2 int) int {
if i1 > i2 {
return i1
}
return i2
}
fn sum_proper_divisors(n u64) u64 {
if n < 2 {
return 0
}
sqrt := u64(math.sqrt(f64(n)))
mut sum := u64(1)
for i := u64(2); i <= sqrt; i++ {
if n % i != 0 {
continue
}
sum += i + n / i
}
if sqrt * sqrt == n {
sum -= sqrt
}
return sum
}
fn classify_sequence(k u64) ([]u64, string) {
if k == 0 {
panic("Argument must be positive.")
}
mut last := k
mut seq := []u64{}
seq << k
for {
last = sum_proper_divisors(last)
seq << last
n := seq.len
mut aliquot := ""
match true {
last == 0 {
aliquot = "Terminating"
}
n == 2 && last == k {
aliquot = "Perfect"
}
n == 3 && last == k {
aliquot = "Amicable"
}
n >= 4 && last == k {
aliquot = "Sociable[${n-1}]"
}
last == seq[n - 2] {
aliquot = "Aspiring"
}
contains(seq[1 .. max_of(1, n - 2)], last) {
aliquot = "Cyclic[${n - 1 - index_of(seq, last)}]"
}
n == 16 || last > threshold {
aliquot = "Non-Terminating"
}
else {}
}
if aliquot != "" {
return seq, aliquot
}
}
return seq, ''
}
fn main() {
println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for k := u64(1); k <= 10; k++ {
seq, aliquot := classify_sequence(k)
println("${k:2}: ${aliquot:-15} $seq")
}
println('')
s := [
u64(11), 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,
]
for k in s {
seq, aliquot := classify_sequence(k)
println("${k:7}: ${aliquot:-15} $seq")
}
println('')
k := u64(15355717786080)
seq, aliquot := classify_sequence(k)
println("$k: ${aliquot:-15} $seq")
}</syntaxhighlight>
 
{{out}}
<pre>
Aliquot classifications - periods for Sociable/Cyclic in square brackets:
 
1: Terminating [1, 0]
2: Terminating [2, 1, 0]
3: Terminating [3, 1, 0]
4: Terminating [4, 3, 1, 0]
5: Terminating [5, 1, 0]
6: Perfect [6, 6]
7: Terminating [7, 1, 0]
8: Terminating [8, 7, 1, 0]
9: Terminating [9, 4, 3, 1, 0]
10: Terminating [10, 8, 7, 1, 0]
 
11: Terminating [11, 1, 0]
12: Terminating [12, 16, 15, 9, 4, 3, 1, 0]
28: Perfect [28, 28]
496: Perfect [496, 496]
220: Amicable [220, 284, 220]
1184: Amicable [1184, 1210, 1184]
12496: Sociable[5] [12496, 14288, 15472, 14536, 14264, 12496]
1264460: Sociable[4] [1264460, 1547860, 1727636, 1305184, 1264460]
790: Aspiring [790, 650, 652, 496, 496]
909: Aspiring [909, 417, 143, 25, 6, 6]
562: Cyclic[2] [562, 284, 220, 284]
1064: Cyclic[2] [1064, 1336, 1184, 1210, 1184]
1488: Non-Terminating [1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384]
 
15355717786080: Non-Terminating [15355717786080, 44534663601120, 144940087464480]
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
{{libheader|Wren-seq}}
<syntaxhighlight lang="wren">import "./fmt" for Conv, Fmt
import "./math" for Int, Nums
import "./seq" for Lst
class Classification {
construct new(seq, aliquot) {
_seq = seq
_aliquot = aliquot
}
seq { _seq}
aliquot { _aliquot }
}
 
var THRESHOLD = 2.pow(47)
var classifySequence = Fn.new { |k|
if (k <= 0) Fiber.abort("K must be positive")
var last = k
var seq = [k]
while (true) {
last = Nums.sum(Int.properDivisors(last))
seq.add(last)
var n = seq.count
var aliquot =
(last == 0) ? "Terminating" :
(n == 2 && last == k) ? "Perfect" :
(n == 3 && last == k) ? "Amicable" :
(n >= 4 && last == k) ? "Sociable[%(n-1)]" :
(last == seq[n-2]) ? "Aspiring" :
(n > 3 && seq[1..n-3].contains(last)) ? "Cyclic[%(n-1-Lst.indexOf(seq, last))]" :
(n == 16 || last > THRESHOLD) ? "Non-terminating" : ""
if (aliquot != "") return Classification.new(seq, aliquot)
}
}
System.print("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for (k in 1..10) {
var c = classifySequence.call(k)
Fmt.print("$2d: $-15s $n", k, c.aliquot, c.seq)
}
System.print()
var a = [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]
for (k in a) {
var c = classifySequence.call(k)
Fmt.print("$7d: $-15s $n", k, c.aliquot, c.seq)
}
System.print()
var k = 15355717786080
var c = classifySequence.call(k)
var seq = c.seq.map { |i| Conv.dec(i) }.toList // ensure 15 digit integer is printed in full
Fmt.print("$d: $-15s $n", k, c.aliquot, seq)</syntaxhighlight>
 
{{out}}
<pre>
Aliquot classifications - periods for Sociable/Cyclic in square brackets:
 
1: Terminating [1, 0]
2: Terminating [2, 1, 0]
3: Terminating [3, 1, 0]
4: Terminating [4, 3, 1, 0]
5: Terminating [5, 1, 0]
6: Perfect [6, 6]
7: Terminating [7, 1, 0]
8: Terminating [8, 7, 1, 0]
9: Terminating [9, 4, 3, 1, 0]
10: Terminating [10, 8, 7, 1, 0]
 
11: Terminating [11, 1, 0]
12: Terminating [12, 16, 15, 9, 4, 3, 1, 0]
28: Perfect [28, 28]
496: Perfect [496, 496]
220: Amicable [220, 284, 220]
1184: Amicable [1184, 1210, 1184]
12496: Sociable[5] [12496, 14288, 15472, 14536, 14264, 12496]
1264460: Sociable[4] [1264460, 1547860, 1727636, 1305184, 1264460]
790: Aspiring [790, 650, 652, 496, 496]
909: Aspiring [909, 417, 143, 25, 6, 6]
562: Cyclic[2] [562, 284, 220, 284]
1064: Cyclic[2] [1064, 1336, 1184, 1210, 1184]
1488: Non-terminating [1488, 2480, 3472, 4464, 8432, 9424, 10416, 21328, 22320, 55056, 95728, 96720, 236592, 459792, 881392, 882384]
 
15355717786080: Non-terminating [15355717786080, 44534663601120, 144940087464480]
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Aliquot_sequence_classifications
// by Galileo, 05/2022
 
sub sumFactors(n)
local i, s
for i = 1 to n / 2
if not mod(n, i) s = s + i
next
return s
end sub
 
sub printSeries(arr(), size, ty$)
local i
print "Integer: ", arr(0), ", Type: ", ty$, ", Series: ";
for i=0 to size-2
print arr(i), " ";
next i
print
end sub
sub alliquot(n)
local arr(16), i, j, ty$
ty$ = "Sociable"
arr(0) = n
for i = 1 to 15
arr(i) = sumFactors(arr(i-1))
if arr(i)=0 or arr(i)=n or (arr(i) = arr(i-1) and arr(i)<>n) then
if arr(i) = 0 then
ty$ = "Terminating"
elsif arr(i) = n and i = 1 then
ty$ = "Perfect"
elsif arr(i) = n and i = 2 then
ty$ = "Amicable"
elsif arr(i) = arr(i-1) and arr(i)<>n then
ty$ = "Aspiring"
end if
printSeries(arr(),i+1,ty$)
return
end if
for j = 1 to i-1
if arr(j) = arr(i) then
printSeries(arr(),i+1,"Cyclic")
return
end if
next j
next i
printSeries(arr(),i+1,"Non-Terminating")
end sub
 
data 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184
data 12496, 1264460, 790, 909, 562, 1064, 1488, 0
 
do
read n
if not n break
alliquot(n)
loop</syntaxhighlight>
{{out}}
<pre>Integer: 1, Type: Terminating, Series: 1
Integer: 2, Type: Terminating, Series: 2 1
Integer: 3, Type: Terminating, Series: 3 1
Integer: 4, Type: Terminating, Series: 4 3 1
Integer: 5, Type: Terminating, Series: 5 1
Integer: 6, Type: Perfect, Series: 6
Integer: 7, Type: Terminating, Series: 7 1
Integer: 8, Type: Terminating, Series: 8 7 1
Integer: 9, Type: Terminating, Series: 9 4 3 1
Integer: 10, Type: Terminating, Series: 10 8 7 1
Integer: 11, Type: Terminating, Series: 11 1
Integer: 12, Type: Terminating, Series: 12 16 15 9 4 3 1
Integer: 28, Type: Perfect, Series: 28
Integer: 496, Type: Perfect, Series: 496
Integer: 220, Type: Amicable, Series: 220 284
Integer: 1184, Type: Amicable, Series: 1184 1210
Integer: 12496, Type: Sociable, Series: 12496 14288 15472 14536 14264
Integer: 1264460, Type: Sociable, Series: 1264460 1547860 1727636 1305184
Integer: 790, Type: Aspiring, Series: 790 650 652 496
Integer: 909, Type: Aspiring, Series: 909 417 143 25 6
Integer: 562, Type: Cyclic, Series: 562 284 220
Integer: 1064, Type: Cyclic, Series: 1064 1336 1184 1210
Integer: 1488, Type: Non-Terminating, Series: 1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384
---Program done, press RETURN---</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) }
fcn aliquot(k){ //-->Walker
Walker(fcn(rk){ k:=rk.value; if(k)rk.set(properDivs(k).sum()); k }.fp(Ref(k)))
}(10).walk(15).println();</langsyntaxhighlight>
Or, refactoring to remove saving the intermediate divisors (and adding white space):
<langsyntaxhighlight lang="zkl">fcn aliquot(k){ //-->Walker
Walker(fcn(rk){
k:=rk.value;
Line 3,377 ⟶ 6,181:
k
}.fp(Ref(k)))
}(10).walk(15).println();</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn classify(k){
const MAX=(2).pow(47); // 140737488355328
ak,aks:=aliquot(k), ak.walk(16);
Line 3,399 ⟶ 6,203:
else "non-terminating" )
+ " " + aks.filter();
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">[1..10].pump(fcn(k){ "%6d is %s".fmt(k,classify(k)).println() });
T(11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488)
.pump(fcn(k){ "%6d is %s".fmt(k,classify(k)).println() });</langsyntaxhighlight>
{{out}}
<pre>
Line 3,435 ⟶ 6,239:
{{trans|AWK}}
This program is correct. However, a bug in the ROM of the ZX Spectrum makes the number 909 of an erroneous result. However, the same program running on Sam BASIC (a superset of Sinclair BASIC that ran on the computer Sam Coupé) provides the correct results.
<langsyntaxhighlight lang="zxbasic">10 PRINT "Number classification sequence"
20 INPUT "Enter a number (0 to end): ";k: IF k>0 THEN GO SUB 2000: PRINT k;" ";s$: GO TO 20
40 STOP
Line 3,475 ⟶ 6,279:
2320 NEXT t
2330 LET s$="non-terminating (after 16 terms)"+s$
2340 RETURN</langsyntaxhighlight>
{{out}}
<pre>Number classification sequence
2,289

edits