Abundant, deficient and perfect number classifications: Difference between revisions

Add ABC
(→‎{{header|C sharp}}: added third method to comparison, added performance comparison.)
(Add ABC)
 
(47 intermediate revisions by 19 users not shown)
Line 28:
=={{header|11l}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="11l">F sum_proper_divisors(n)
R I n < 2 {0} E sum((1 .. n I/ 2).filter(it -> (@n % it) == 0))
 
Line 46:
print(‘Deficient = ’deficient)
print(‘Perfect = ’perfect)
print(‘Abundant = ’abundant)</langsyntaxhighlight>
{{out}}
<pre>
Line 58:
For maximum compatibility, this program uses only the basic instruction set (S/360)
with 2 ASSIST macros (XDECO,XPRNT).
<langsyntaxhighlight lang="360asm">* Abundant, deficient and perfect number 08/05/2016
ABUNDEFI CSECT
USING ABUNDEFI,R13 set base register
Line 113:
XDEC DS CL12
REGEQU
END ABUNDEFI</langsyntaxhighlight>
{{out}}
<pre>
Line 119:
</pre>
=={{header|8086 Assembly}}==
<langsyntaxhighlight lang="asm">LIMIT: equ 20000
cpu 8086
org 100h
Line 199:
db '.....'
snum: db 13,10,'$'
data: equ $</langsyntaxhighlight>
{{out}}
<pre>Deficient: 15043
Line 207:
=={{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">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program numberClassif64.s */
Line 670:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 678:
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">PUT 0 IN deficient
PUT 0 IN perfect
PUT 0 IN abundant
 
HOW TO FIND PROPER DIVISOR SUMS UP TO limit:
SHARE p
PUT {} IN p
FOR i IN {0..limit}: PUT 0 IN p[i]
FOR i IN {1..floor (limit/2)}:
PUT i+i IN j
WHILE j <= limit:
PUT p[j]+i IN p[j]
PUT j+i IN j
 
HOW TO CLASSIFY n:
SHARE deficient, perfect, abundant, p
SELECT:
p[n] < n: PUT deficient+1 IN deficient
p[n] = n: PUT perfect+1 IN perfect
p[n] > n: PUT abundant+1 IN abundant
 
PUT 20000 IN limit
FIND PROPER DIVISOR SUMS UP TO limit
FOR n IN {1..limit}: CLASSIFY n
 
WRITE deficient, "deficient"/
WRITE perfect, "perfect"/
WRITE abundant, "abundant"/</syntaxhighlight>
{{out}}
<Pre>15043 deficient
4 perfect
4953 abundant</Pre>
=={{header|Action!}}==
Because of the memory limitation on the non-expanded Atari 8-bit computer the array containing Proper Divisor Sums is generated and used twice for the first and the second half of numbers separately.
<langsyntaxhighlight Actionlang="action!">PROC FillSumOfDivisors(CARD ARRAY pds CARD size,maxNum,offset)
CARD i,j
 
Line 732 ⟶ 765:
PrintF(" Perfect: %I%E",perf)
PrintF(" Abudant: %I%E",abud)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Abundant,_deficient_and_perfect_number_classifications_v2.png Screenshot from Atari 8-bit computer]
Line 747 ⟶ 780:
[[http://rosettacode.org/wiki/Proper_divisors#Ada]].
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Generic_Divisors;
 
procedure ADB_Classification is
Line 781 ⟶ 814:
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line("====================");
end ADB_Classification;</langsyntaxhighlight>
 
{{out}}
Line 792 ⟶ 825:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN # classify the numbers 1 : 20 000 as abudant, deficient or perfect #
INT abundant count := 0;
INT deficient count := 0;
INT perfect count := 0;
INT abundant example := 0;
INT deficient example := 0;
INT perfect example := 0;
INT max number = 20 000;
# construct a table of the proper divisor sums #
Line 809 ⟶ 839:
# classify the numbers #
FOR n TO max number DO
IF INT pd sum = pds[ n ];
IF pd sum < n THEN
THEN deficient count +:= 1
ELIF pd sum = n THEN
# have a deficient number #
deficientperfect count +:= 1;
deficient example := n
ELIF pd sum = n
THEN
# have a perfect number #
perfect count +:= 1;
perfect example := n
ELSE # pd sum > n #
# have an abundant number count +:= #1
abundant count +:= 1;
abundant example := n
FI
OD;
print( ( "abundant ", whole( abundant count, 0 ), newline ) );
# displays the classification, count and example #
print( ( "deficient ", whole( deficient count, 0 ), newline ) );
PROC show result = ( STRING classification, INT count, example )VOID:
print( ( "perfect ", whole( perfect count, 0 ), newline ) )
print( ( "There are "
END
, whole( count, -8 )
</syntaxhighlight>
, " "
, classification
, " numbers up to "
, whole( max number, 0 )
, " e.g.: "
, whole( example, 0 )
, newline
)
);
 
# show how many of each type of number there are and an example #
show result( "abundant ", abundant count, abundant example );
show result( "deficient", deficient count, deficient example );
show result( "perfect ", perfect count, perfect example )
END</lang>
{{out}}
<pre>
abundant 4953
There are 4953 abundant numbers up to 20000 e.g.: 20000
deficient 15043
There are 15043 deficient numbers up to 20000 e.g.: 19999
perfect 4
There are 4 perfect numbers up to 20000 e.g.: 8128
</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin % count abundant, perfect and deficient numbers up to 20 000 %
integer MAX_NUMBER;
MAX_NUMBER := 20000;
Line 876 ⟶ 884:
write( "Deficient numbers up to 20 000: ", dCount )
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 885 ⟶ 893:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">on aliquotSum(n)
if (n < 2) then return 0
set sum to 1
Line 917 ⟶ 925:
end task
 
task()</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{deficient:15043, perfect:4, abundant:4953}</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program numberClassif.s */
Line 987 ⟶ 995:
blt 2f
lsl r5,r4,#1 @ number * 2
cmp r5,r1 @ compare number ansand sum
addeq r7,r7,#1 @ perfect
addgt r6,r6,#1 @ deficient
Line 1,050 ⟶ 1,058:
/* r1 contains address of divisors area */
/* r0 return divisors items in table */
/* r1 return the numbersum of odd divisors */
/* r2 return the sum of divisors */
decompFact:
push {r3-r12,lr} @ save registers
Line 1,379 ⟶ 1,386:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 1,387 ⟶ 1,394:
</pre>
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">properDivisors: function [n]->
(factors n) -- n
 
Line 1,403 ⟶ 1,410:
print ["Found" abundant "abundant,"
deficient "deficient and"
perfect "perfect numbers."]</langsyntaxhighlight>
{{out}}
Line 1,410 ⟶ 1,417:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">Loop
{
m := A_index
Line 1,462 ⟶ 1,469:
 
esc::ExitApp
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,479 ⟶ 1,486:
=={{header|AWK}}==
works with GNU Awk 3.1.5 and with BusyBox v1.21.1
<syntaxhighlight lang="awk">
<lang AWK>
#!/bin/gawk -f
function sumprop(num, i,sum,root) {
Line 1,516 ⟶ 1,523:
print "Deficient: " deficient
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,528 ⟶ 1,535:
=={{header|Batch File}}==
As batch files aren't particularly well-suited to increasingly large arrays of data, this code will chew through processing power.
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 1,562 ⟶ 1,569:
 
exit /b %sumdivisers%
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
{{works with|Chipmunk Basic}}
<lang BASIC>10 DEFINT A-Z: LM=20000
{{works with|GW-BASIC}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="basic">10 DEFINT A-Z: LM=20000
20 DIM P(LM)
30 FOR I=1 TO LM: P(I)=-32767: NEXT
Line 1,575 ⟶ 1,586:
90 PRINT "DEFICIENT:";D
100 PRINT "PERFECT:";P
110 PRINT "ABUNDANT:";A</langsyntaxhighlight>
{{out}}
<pre>DEFICIENT: 15043
PERFECT: 4
ABUNDANT: 4953</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="vb">deficient = 0
perfect = 0
abundant = 0
 
for n = 1 to 20000
sum = SumProperDivisors(n)
begin case
case sum < n
deficient += 1
case sum = n
perfect += 1
else
abundant += 1
end case
next
 
print "The classification of the numbers from 1 to 20,000 is as follows :"
print
print "Deficient = "; deficient
print "Perfect = "; perfect
print "Abundant = "; abundant
end
 
function SumProperDivisors(number)
if number < 2 then return 0
sum = 0
for i = 1 to number \ 2
if number mod i = 0 then sum += i
next i
return sum
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 cls
110 defic = 0
120 perfe = 0
130 abund = 0
140 for n = 1 to 20000
150 sump = SumProperDivisors(n)
160 if sump < n then
170 defic = defic+1
180 else
190 if sump = n then
200 perfe = perfe+1
210 else
220 if sump > n then abund = abund+1
230 endif
240 endif
250 next
260 print "The classification of the numbers from 1 to 20,000 is as follows :"
270 print
280 print "Deficient = ";defic
290 print "Perfect = ";perfe
300 print "Abundant = ";abund
310 end
320 function SumProperDivisors(number)
330 if number < 2 then SumProperDivisors = 0
340 sum = 0
350 for i = 1 to number/2
360 if number mod i = 0 then sum = sum+i
370 next i
380 SumProperDivisors = sum
390 end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Dim sum As Integer, deficient As Integer, perfect As Integer, abundant As Integer
For n As Integer = 1 To 20000
sum = SumProperDivisors(n)
If sum < n Then
deficient += 1
Else If sum = n Then
perfect += 1
Else
abundant += 1
Endif
Next
Print "The classification of the numbers from 1 to 20,000 is as follows : \n"
Print "Deficient = "; deficient
Print "Perfect = "; perfect
Print "Abundant = "; abundant
End
 
Function SumProperDivisors(number As Integer) As Integer
If number < 2 Then Return 0
Dim sum As Integer = 0
For i As Integer = 1 To number \ 2
If number Mod i = 0 Then sum += i
Next
Return sum
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
The [[#BASIC|BASIC]] solution works without any changes.
 
==={{header|QBasic}}===
The [[#BASIC|BASIC]] solution works without any changes.
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="vb">function sumProperDivisors(num)
if num > 1 then
sum = 1
root = sqr(num)
for i = 2 to root
if num mod i = 0 then
sum = sum + i
if (i*i) <> num then sum = sum + num / i
end if
next i
end if
sumProperDivisors = sum
end function
 
deficient = 0
perfect = 0
abundant = 0
 
print "The classification of the numbers from 1 to 20,000 is as follows :"
 
for n = 1 to 20000
sump = sumProperDivisors(n)
if sump < n then
deficient = deficient +1
else
if sump = n then
perfect = perfect +1
else
if sump > n then abundant = abundant +1
end if
end if
next n
 
print "Deficient = "; deficient
print "Perfect = "; perfect
print "Abundant = "; abundant</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET lm = 20000
DIM s(0)
MAT REDIM s(lm)
 
FOR i = 1 TO lm
LET s(i) = -32767
NEXT i
FOR i = 1 TO lm/2
FOR j = i+i TO lm STEP i
LET s(j) = s(j) +i
NEXT j
NEXT i
 
FOR i = 1 TO lm
LET x = i - 32767
IF s(i) < x THEN
LET d = d +1
ELSE
IF s(i) = x THEN
LET p = p +1
ELSE
LET a = a +1
END IF
END IF
NEXT i
 
PRINT "The classification of the numbers from 1 to 20,000 is as follows :"
PRINT
PRINT "Deficient ="; d
PRINT "Perfect ="; p
PRINT "Abundant ="; a
END</syntaxhighlight>
{{out}}
<pre>Similar to FreeBASIC entry.</pre>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
manifest $( maximum = 20000 $)
 
Line 1,612 ⟶ 1,811:
writef("Abundant numbers: %N*N", ab)
freevec(p)
$)</langsyntaxhighlight>
{{out}}
<pre>Deficient numbers: 15043
Line 1,622 ⟶ 1,821:
This is not a particularly efficient implementation, so unless you're using a compiler, you can expect it to take a good few minutes to complete. But you can always test with a shorter range of numbers by replacing the 20000 (<tt>"2":*8*</tt>) near the start of the first line.
 
<langsyntaxhighlight lang="befunge">p0"2":*8*>::2/\:2/\28*:*:**+>::28*:*:*/\28*:*:*%%#v_\:28*:*:*%v>00p:0`\0\`-1v
++\1-:1`#^_$:28*:*:*/\28*vv_^#<<<!%*:*:*82:-1\-1\<<<\+**:*:*82<+>*:*:**\2-!#+
v"There are "0\g00+1%*:*:<>28*:*:*/\28*:*:*/:0\`28*:*:**+-:!00g^^82!:g01\p01<
>:#,_\." ,tneicifed">:#,_\." dna ,tcefrep">:#,_\.55+".srebmun tnadnuba">:#,_@</langsyntaxhighlight>
 
{{out}}
Line 1,633 ⟶ 1,832:
=={{header|Bracmat}}==
Two solutions are given. The first solution first decomposes the current number into a multiset of prime factors and then constructs the proper divisors. The second solution finds proper divisors by checking all candidates from 1 up to the square root of the given number. The first solution is a few times faster, because establishing the prime factors of a small enough number (less than 2^32 or less than 2^64, depending on the bitness of Bracmat) is fast.
<langsyntaxhighlight lang="bracmat">( clk$:?t0
& ( multiples
= prime multiplicity
Line 1,705 ⟶ 1,904:
& clk$:?t3
& out$(flt$(!t3+-1*!t2,2) sec)
);</langsyntaxhighlight>
Output:
<pre>deficient 15043 perfect 4 abundant 4953
Line 1,713 ⟶ 1,912:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang c>
#include<stdio.h>
#define de 0
Line 1,756 ⟶ 1,955:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,762 ⟶ 1,961:
</pre>
 
=={{header|C sharp|C#}}==
Three algorithms presented, the first is fast, but can be a memory hog when tabulating to larger limits. The second is slower, but doesn't have any memory issue. The third is quite a bit slower, but the code may be easier to follow.
 
Line 1,771 ⟶ 1,970:
Third method:
:Uses a loop with a inner Enumerable.Range reaching to i / 2, only adding one divisor at a time.
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,834 ⟶ 2,033:
deficient = bound - abundant - perfect;
}
}</langsyntaxhighlight>
{{out|Output @ Tio.run}}
We see the second method is about 10 times slower than the first method, and the third method more than 120 times slower than the second method.
Line 1,844 ⟶ 2,043:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include <vector>
Line 1,876 ⟶ 2,075:
std::cout << "Abundant : " << abundants.size( ) << std::endl ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>Deficient : 15043
Line 1,884 ⟶ 2,083:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
 
function divisors(Integer int) =>
Line 1,896 ⟶ 2,095:
print("perfect: ``counts[equal] else "none"``");
print("abundant: ``counts[larger] else "none"``");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,904 ⟶ 2,103:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn pad-class
[n]
(let [divs (filter #(zero? (mod n %)) (range 1 n))
Line 1,920 ⟶ 2,119:
{:perfect (count (filter #(= % :perfect) classes))
:abundant (count (filter #(= % :abundant) classes))
:deficient (count (filter #(= % :deficient) classes))}))</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="clojure">(count-classes 20000)
;=> {:perfect 4,
; :abundant 4953,
; :deficient 15043}</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Generate proper divisors from 1 to max
proper_divisors = proc (max: int) returns (array[int])
divs: array[int] := array[int]$fill(1, max, 0)
for i: int in int$from_to(1, max/2) do
for j: int in int$from_to_by(i*2, max, i) do
divs[j] := divs[j] + i
end
end
return(divs)
end proper_divisors
 
% Classify all the numbers for which we have divisors
classify = proc (divs: array[int]) returns (int, int, int)
def, per, ab: int
def, per, ab := 0, 0, 0
for i: int in array[int]$indexes(divs) do
if divs[i]<i then def := def + 1
elseif divs[i]=i then per := per + 1
elseif divs[i]>i then ab := ab + 1
end
end
return(def, per, ab)
end classify
 
% Find amount of deficient, perfect, and abundant numbers up to 20000
start_up = proc ()
max = 20000
po: stream := stream$primary_output()
def, per, ab: int := classify(proper_divisors(max))
stream$putl(po, "Deficient: " || int$unparse(def))
stream$putl(po, "Perfect: " || int$unparse(per))
stream$putl(po, "Abundant: " || int$unparse(ab))
end start_up</syntaxhighlight>
{{out}}
<pre>Deficient: 15043
Perfect: 4
Abundant: 4953</pre>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun number-class (n)
(let ((divisor-sum (sum-divisors n)))
(cond ((< divisor-sum n) :deficient)
Line 1,948 ⟶ 2,188:
:count (eq class :perfect) :into perfect
:count (eq class :abundant) :into abundant
:finally (return (values deficient perfect abundant))))</langsyntaxhighlight>
 
Output:
Line 1,958 ⟶ 2,198:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
const MAXIMUM := 20000;
Line 1,994 ⟶ 2,234:
print_i16(def); print(" deficient numbers.\n");
print_i16(per); print(" perfect numbers.\n");
print_i16(ab); print(" abundant numbers.\n");</langsyntaxhighlight>
{{out}}
<pre>15043 deficient numbers.
Line 2,001 ⟶ 2,241:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() /*@safe*/ {
import std.stdio, std.algorithm, std.range;
 
Line 2,018 ⟶ 2,258:
//iota(1, 1 + rangeMax).map!classify.hashGroup.writeln;
iota(1, 1 + rangeMax).map!classify.array.sort().group.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[Tuple!(Class, uint)(deficient, 15043), Tuple!(Class, uint)(perfect, 4), Tuple!(Class, uint)(abundant, 4953)]</pre>
Line 2,024 ⟶ 2,264:
=={{header|Delphi}}==
See [[#Pascal]].
=={{header|Draco}}==
<syntaxhighlight lang="draco">/* Fill a given array such that for each N,
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
word i, j, max;
max := dim(p,1)-1;
for i from 0 upto max do p[i] := 0 od;
for i from 1 upto max/2 do
for j from i*2 by i upto max do
p[j] := p[j] + i
od
od
corp
 
proc nonrec main() void:
word MAX = 20000;
word def, per, ab, i;
/* Find all required proper divisor sums */
[MAX+1] word p;
propdivs(p);
def := 0;
per := 0;
ab := 0;
/* Check each number */
for i from 1 upto MAX do
if p[i]<i then def := def + 1
elif p[i]=i then per := per + 1
elif p[i]>i then ab := ab + 1
fi
od;
writeln("Deficient: ", def:5);
writeln("Perfect: ", per:5);
writeln("Abundant: ", ab:5)
corp</syntaxhighlight>
{{out}}
<pre>Deficient: 15043
Perfect: 4
Abundant: 4953</pre>
 
=={{header|Dyalect}}==
 
{{trans|C#}}
 
<langsyntaxhighlight lang="dyalect">func sieve(bound) {
var (a, d, p) = (0, 0, 0)
var sum = Array.emptyEmpty(bound + 1, 0)
for divisor in 1..(bound / 2) {
Line 2,051 ⟶ 2,334:
(abundant: a, deficient: d, perfect: p)
}
 
func divisionIterator.Where(boundfn) {
funcfor Iterator.where(fn)x in this {
forif fn(x in this) {
ifyield fn(x) {
yield x
}
}
}
}
func Iterator.sum() {
 
var sum = 0
func Iterator.Sum() {
for x in this {
var sum += x0
for x in this }{
sum += x
}
sum
}
func division(bound) {
var (a, d, p) = (0, 0, 0)
for i in 1..20000 {
var sum = ( 1 .. ((i + 1) / 2) )
.whereWhere(div => div != i && i % div == 0)
.sumSum()
if sum < i {
d += 1
Line 2,085 ⟶ 2,370:
func out(res) {
print("Abundant: \(res::.abundant), Deficient: \(res::.deficient), Perfect: \(res::.perfect)");
}
out( sieve(20000) )
out( division(20000) )</langsyntaxhighlight>
 
{{out}}
Line 2,095 ⟶ 2,380:
<pre>Abundant: 4953, Deficient: 15043, Perfect: 4
Abundant: 4953, Deficient: 15043, Perfect: 4</pre>
 
=={{header|EasyLang}}==
{{trans|AWK}}
 
<syntaxhighlight lang=easylang>
func sumprop num .
if num < 2
return 0
.
i = 2
sum = 1
root = sqrt num
while i < root
if num mod i = 0
sum += i + num / i
.
i += 1
.
if num mod root = 0
sum += root
.
return sum
.
for j = 1 to 20000
sump = sumprop j
if sump < j
deficient += 1
elif sump = j
perfect += 1
else
abundant += 1
.
.
print "Perfect: " & perfect
print "Abundant: " & abundant
print "Deficient: " & deficient
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'math) ;; sum-divisors function
 
Line 2,123 ⟶ 2,445:
deficient 15043
perfect 4
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
{{trans|Haskell}}
 
<langsyntaxhighlight lang="ela">open monad io number list
 
divisors n = filter ((0 ==) << (n `mod`)) [1 .. (n `div` 2)]
Line 2,138 ⟶ 2,460:
printRes "deficient: " LT
printRes "perfect: " EQ
printRes "abundant: " GT</langsyntaxhighlight>
 
{{out}}
Line 2,147 ⟶ 2,469:
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
 
classifyNumbers(int bound, ref int abundant, ref int deficient, ref int perfect)
Line 2,157 ⟶ 2,479:
int[] sum := new int[](bound + 1);
for(int divisor := 1,; divisor <= bound / 2,; divisor += 1)
{
for(int i := divisor + divisor,; i <= bound,; i += divisor)
{
sum[i] := sum[i] + divisor
Line 2,165 ⟶ 2,487:
};
for(int i := 1,; i <= bound,; i += 1)
{
int t := sum[i];
Line 2,198 ⟶ 2,520:
classifyNumbers(20000, ref abundant, ref deficient, ref perfect);
console.printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,205 ⟶ 2,527:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Proper do
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
Line 2,223 ⟶ 2,545:
end
end)
IO.puts "Deficient: #{deficient} Perfect: #{perfect} Abundant: #{abundant}"</langsyntaxhighlight>
 
{{out}}
Line 2,231 ⟶ 2,553:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(properdivs).
-export([divs/1,sumdivs/1,class/1]).
Line 2,263 ⟶ 2,585:
class(D,P,A,Sum,Acc,L) when Acc > Sum ->
class(D+1,P,A,sumdivs(Acc+1),Acc+1,L).
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,279 ⟶ 2,601:
===Erlang 2===
The version above is not tail-call recursive, and so cannot classify large ranges. Here is a more optimal solution.
<langsyntaxhighlight lang="erlang">
-module(proper_divisors).
-export([classify_range/2]).
Line 2,309 ⟶ 2,631:
proper_divisors(I, L, N, A) ->
proper_divisors(I+1, L, N, [N div I, I|A]).
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 2,316 ⟶ 2,638:
</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="f#">
<lang F#>
let mutable a=0
let mutable b=0
Line 2,339 ⟶ 2,661:
printfn "perfect %i"d
printfn "abundant %i"e
</syntaxhighlight>
</lang>
 
An immutable solution.
<langsyntaxhighlight lang="fsharp">
let deficient, perfect, abundant = 0,1,2
 
Line 2,356 ⟶ 2,678:
|> List.zip [ "deficient"; "perfect"; "abundant" ]
|> List.iter (fun (label, count) -> printfn "%s: %d" label count)
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">
USING: fry math.primes.factors math.ranges ;
: psum ( n -- m ) divisors but-last sum ;
Line 2,368 ⟶ 2,690:
[ +eq+ pcount "Perfect: " write . ]
[ +gt+ pcount "Abundant: " write . ] tri
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,378 ⟶ 2,700:
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<langsyntaxhighlight Forthlang="forth">CREATE A 0 ,
: SLOT ( x y -- 0|1|2) OVER OVER < -ROT > - 1+ ;
: CLASSIFY ( n -- n') \ 0 == deficient, 1 == perfect, 2 == abundant
Line 2,403 ⟶ 2,725:
." Perfect : " [ COUNTS 1 CELLS + ]L @ . CR
." Abundant : " [ COUNTS 2 CELLS + ]L @ . CR ;
20000 CLASSIFY-NUMBERS .COUNTS BYE</langsyntaxhighlight>
{{out}}
<pre>Deficient : 15043
Line 2,420 ⟶ 2,742:
Abundant 4953
 
<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 2,459 ⟶ 2,781:
WRITE (6,*) "Abundant ",COUNT(TEST .GT. 0) !Alternatively, make one pass with three counts.
END !Done.
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
' FreeBASIC v1.05.0 win64
 
Line 2,496 ⟶ 2,818:
Sleep
End
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,508 ⟶ 2,830:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
d = new dict
for n = 1 to 20000
Line 2,520 ⟶ 2,842:
println["Perfect: " + d@0]
println["Abundant: " + d@1]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,527 ⟶ 2,849:
Abundant: 4953
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn SumProperDivisors( number as long ) as long
long i, result, sum = 0
if number < 2 then exit fn = 0
for i = 1 to number / 2
if number mod i == 0 then sum += i
next
result = sum
end fn = result
 
void local fn NumberCategories( limit as long )
long i, sum, deficient = 0, perfect = 0, abundant = 0
for i = 1 to limit
sum = fn SumProperDivisors(i)
if sum < i then deficient++ : continue
if sum == i then perfect++ : continue
abundant++
next
printf @"\nClassification of integers from 1 to %ld is:\n", limit
printf @"Deficient = %ld\nPerfect = %ld\nAbundant = %ld", deficient, perfect, abundant
printf @"-----------------\nTotal = %ld\n", deficient + perfect + abundant
end fn
 
CFTimeInterval t
t = fn CACurrentMediaTime
fn NumberCategories( 20000 )
printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Classification of integers from 1 to 20000 is:
 
Deficient = 15043
Perfect = 4
Abundant = 4953
-----------------
Total = 20000
 
Compute time: 1761.443 ms
</pre>
 
 
=={{header|GFA Basic}}==
 
<syntaxhighlight lang="text">
num_deficient%=0
num_perfect%=0
Line 2,576 ⟶ 2,945:
RETURN sum%
ENDFUNC
</syntaxhighlight>
</lang>
 
Output is:
Line 2,586 ⟶ 2,955:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,615 ⟶ 2,984:
fmt.Printf("There are %d abundant numbers between 1 and 20000\n", a)
fmt.Printf("There are %d perfect numbers between 1 and 20000\n", p)
}</langsyntaxhighlight>
 
{{out}}
Line 2,627 ⟶ 2,996:
=====Solution:=====
Uses the "factorize" closure from [[Factors of an integer]]
<langsyntaxhighlight Groovylang="groovy">def dpaCalc = { factors ->
def n = factors.pop()
def fSum = factors.sum()
Line 2,641 ⟶ 3,010:
map
}
.each { e -> println e }</langsyntaxhighlight>
{{out}}
<pre>deficient=15043
Line 2,648 ⟶ 3,017:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
 
Line 2,660 ⟶ 3,029:
printRes "deficient: " LT
printRes "perfect: " EQ
printRes "abundant: " GT</langsyntaxhighlight>
{{out}}
<pre>deficient: 15043
Line 2,668 ⟶ 3,037:
Or, a little faster and more directly, as a single fold:
 
<langsyntaxhighlight lang="haskell">import Data.Numbers.Primes (primeFactors)
import Data.List (group, sort)
 
Line 2,687 ⟶ 3,056:
 
main :: IO ()
main = print $ deficientPerfectAbundantCountsUpTo 20000</langsyntaxhighlight>
{{Out}}
<pre>(15043,4,4953)</pre>
Line 2,694 ⟶ 3,063:
[[Proper divisors#J|Supporting implementation]]:
 
<langsyntaxhighlight Jlang="j">factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
properDivisors=: factors -. ]</langsyntaxhighlight>
 
We can subtract the sum of a number's proper divisors from itself to classify the number:
 
<langsyntaxhighlight Jlang="j"> (- +/@properDivisors&>) 1+i.10
1 1 2 1 4 0 6 1 5 2</langsyntaxhighlight>
 
Except, we are only concerned with the sign of this difference:
 
<langsyntaxhighlight Jlang="j"> *(- +/@properDivisors&>) 1+i.30
1 1 1 1 1 0 1 1 1 1 1 _1 1 1 1 1 1 _1 1 _1 1 1 1 _1 1 1 1 0 1 _1</langsyntaxhighlight>
 
Also, we do not care about the individual classification but only about how many numbers fall in each category:
 
<langsyntaxhighlight Jlang="j"> #/.~ *(- +/@properDivisors&>) 1+i.20000
15043 4 4953</langsyntaxhighlight>
 
So: 15043 deficient, 4 perfect and 4953 abundant numbers in this range.
Line 2,716 ⟶ 3,085:
How do we know which is which? We look at the unique values (which are arranged by their first appearance, scanning the list left to right):
 
<langsyntaxhighlight Jlang="j"> ~. *(- +/@properDivisors&>) 1+i.20000
1 0 _1</langsyntaxhighlight>
 
The sign of the difference is negative for the abundant case - where the sum is greater than the number. And we rely on order being preserved in sequences (this happens to be a fundamental property of computer memory, also).
Line 2,723 ⟶ 3,092:
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.stream.LongStream;
 
public class NumberClassifications {
Line 2,749 ⟶ 3,118:
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n != i && n % i == 0).sum();
}
}</langsyntaxhighlight>
 
<pre>Deficient: 15043
Line 2,758 ⟶ 3,127:
 
===ES5===
<langsyntaxhighlight Javascriptlang="javascript">for (var dpa=[1,0,0], n=2; n<=20000; n+=1) {
for (var ds=0, d=1, e=n/2+1; d<e; d+=1) if (n%d==0) ds+=d
dpa[ds<n ? 0 : ds==n ? 1 : 2]+=1
}
document.write('Deficient:',dpa[0], ', Perfect:',dpa[1], ', Abundant:',dpa[2], '<br>' )</langsyntaxhighlight>
'''Or:'''
<langsyntaxhighlight Javascriptlang="javascript">for (var dpa=[1,0,0], n=2; n<=20000; n+=1) {
for (var ds=1, d=2, e=Math.sqrt(n); d<e; d+=1) if (n%d==0) ds+=d+n/d
if (n%e==0) ds+=e
dpa[ds<n ? 0 : ds==n ? 1 : 2]+=1
}
document.write('Deficient:',dpa[0], ', Perfect:',dpa[1], ', Abundant:',dpa[2], '<br>' )</langsyntaxhighlight>
'''Or:'''
<langsyntaxhighlight Javascriptlang="javascript">function primes(t) {
var ps = {2:true, 3:true}
next: for (var n=5, i=2; n<=t; n+=i, i=6-i) {
Line 2,818 ⟶ 3,187:
dpa[ds<n ? 0 : ds==n ? 1 : 2]+=1
}
document.write('Deficient:',dpa[0], ', Perfect:',dpa[1], ', Abundant:',dpa[2], '<br>' )</langsyntaxhighlight>
{{output}}
<pre>Deficient:15043, Perfect:4, Abundant:4953</pre>
Line 2,824 ⟶ 3,193:
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,865 ⟶ 3,234:
.length.toString())
.join('\n');
})();</langsyntaxhighlight>
 
{{Out}}
Line 2,871 ⟶ 3,240:
perfect: 4
abundant: 4953</pre>
 
{{Trans|Lua}}
<syntaxhighlight lang="javascript">
// classify the numbers 1 : 20 000 as abudant, deficient or perfect
"use strict"
let abundantCount = 0
let deficientCount = 0
let perfectCount = 0
const maxNumber = 20000
// construct a table of the proper divisor sums
let pds = []
pds[ 1 ] = 0
for( let i = 2; i <= maxNumber; i ++ ){ pds[ i ] = 1 }
for( let i = 2; i <= maxNumber; i ++ )
{
for( let j = i + i; j <= maxNumber; j += i ){ pds[ j ] += i }
}
// classify the numbers
for( let n = 1; n <= maxNumber; n ++ )
{
if( pds[ n ] < n )
{
deficientCount ++
}
else if( pds[ n ] == n )
{
perfectCount ++
}
else // pds[ n ] > n
{
abundantCount ++
}
}
console.log( "abundant " + abundantCount.toString() )
console.log( "deficient " + deficientCount.toString() )
console.log( "perfect " + perfectCount.toString() )
</syntaxhighlight>
{{out}}
<pre>
abundant 4953
deficient 15043
perfect 4
</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
The definition of proper_divisors is taken from [[Proper_divisors#jq]]:
<langsyntaxhighlight lang="jq"># unordered
def proper_divisors:
. as $n
Line 2,885 ⟶ 3,297:
end)
else empty
end;</langsyntaxhighlight>
'''The task:'''
<langsyntaxhighlight lang="jq">def sum(stream): reduce stream as $i (0; . + $i);
 
def classify:
Line 2,894 ⟶ 3,306:
| if . < $n then "deficient" elif . == $n then "perfect" else "abundant" end;
 
reduce (range(1; 20001) | classify) as $c ({}; .[$c] += 1 )</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -c -f AbundantDeficientPerfect.jq
{"deficient":15043,"perfect":4,"abundant":4953}</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript ES5 entry.
 
<langsyntaxhighlight lang="javascript">/* Classify Deficient, Perfect and Abdundant integers */
function classifyDPA(stop:number, start:number=0, step:number=1):array {
var dpa = [1, 0, 0];
Line 2,913 ⟶ 3,325:
 
var dpa = classifyDPA(20000, 2);
printf('Deficient: %d, Perfect: %d, Abundant: %d\n', dpa[0], dpa[1], dpa[2]);</langsyntaxhighlight>
 
{{out}}
Line 2,937 ⟶ 3,349:
<code>divisorsum</code> calculates the sum of aliquot divisors. It uses <code>pcontrib</code> to calculate the contribution of each prime factor.
 
<syntaxhighlight lang="julia">
<lang Julia>
function pcontrib(p::Int64, a::Int64)
n = one(p)
Line 2,955 ⟶ 3,367:
dsum -= n
end
</syntaxhighlight>
</lang>
Perhaps <code>pcontrib</code> could be made more efficient by caching results to avoid repeated calculations.
 
Line 2,962 ⟶ 3,374:
Use a three element array, <code>iclass</code>, rather than three separate variables to tally the classifications. Take advantage of the fact that the sign of <code>divisorsum(n) - n</code> depends upon its class to increment <code>iclass</code>. 1 is a difficult case, it is deficient by convention, so I manually add its contribution and start the accumulation with 2. All primes are deficient, so I test for those and tally accordingly, bypassing <code>divisorsum</code>.
 
<syntaxhighlight lang="julia">
<lang Julia>
const L = 2*10^4
iclasslabel = ["Deficient", "Perfect", "Abundant"]
Line 2,980 ⟶ 3,392:
println(" ", iclasslabel[i], ", ", iclass[i])
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,989 ⟶ 3,401:
Abundant, 4953
</code>
 
=== Using Primes versions >= 0.5.4 ===
Recent revisions of the Primes package include a divisors() which returns divisors of n including 1 and n.
<syntaxhighlight lamg = "julia">using Primes
 
""" Return tuple of (perfect, abundant, deficient) counts from 1 up to nmax """
function per_abu_def_classify(nmax::Int)
results = [0, 0, 0]
for n in 1:nmax
results[sign(sum(divisors(n)) - 2 * n) + 2] += 1
end
return (perfect, abundant, deficient) = results
end
 
let MAX = 20_000
NPE, NAB, NDE = per_abu_def_classify(MAX)
println("$NPE perfect, $NAB abundant, and $NDE deficient numbers in 1:$MAX.")
end
</syntaxhighlight>{{out}}<pre>4 perfect, 4953 abundant, and 15043 deficient numbers in 1:20000.</pre>
 
=={{header|K}}==
{{works with|Kona}}
<lang K>
<syntaxhighlight lang="k">
/Classification of numbers into abundant, perfect and deficient
/ numclass.k
Line 3,003 ⟶ 3,435:
`0: ,"Perfect = ", $(#c[1])
`0: ,"Abundant = ", $(#c[2])
</syntaxhighlight>
</lang>
 
 
 
{{works with|ngn/k}}<syntaxhighlight lang="k">/Classification of numbers into abundant, perfect and deficient
/ numclass.k
 
/return 0,1 or -1 if perfect or abundant or deficient respectively
numclass: {s:(+/&~(!1+x)!\:x)-x; $[s>x;:1;$[s<x;:-1;:0]]}
/classify numbers from 1 to 20000 into respective groups
c: =numclass' 1+!20000
/print statistics
`0: ,"Deficient = ", $(#c[-1])
`0: ,"Perfect = ", $(#c[0])
`0: ,"Abundant = ", $(#c[1])
</syntaxhighlight>
 
(indentation optional, used to emphasize lines which are not comment lines)
 
 
{{out}}
<pre>
Line 3,009 ⟶ 3,460:
Perfect = 4
Abundant = 4953
 
</pre>
 
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1
 
fun sumProperDivisors(n: Int) =
Line 3,038 ⟶ 3,488:
println("Perfect = $perfect")
println("Abundant = $abundant")
}</langsyntaxhighlight>
 
{{out}}
Line 3,050 ⟶ 3,500:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "ROSETTA CODE - Abundant, deficient and perfect number classifications"
print
Line 3,100 ⟶ 3,550:
next y
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,126 ⟶ 3,576:
 
=={{header|Lua}}==
===Summing the factors using modulo/division===
<lang Lua>function sumDivs (n)
<syntaxhighlight lang="lua">function sumDivs (n)
if n < 2 then return 0 end
local sum, sr = 1, math.sqrt(n)
Line 3,147 ⟶ 3,598:
print("Abundant:", a)
print("Deficient:", d)
print("Perfect:", p)</langsyntaxhighlight>
{{out}}
<pre>Abundant: 4953
Deficient: 15043
Perfect: 4</pre>
 
===Summing the factors using a table===
{{Trans|ALGOL 68}}
<syntaxhighlight lang="lua">
do -- classify the numbers 1 : 20 000 as abudant, deficient or perfect
local abundantCount = 0
local deficientCount = 0
local perfectCount = 0
local maxNumber = 20000
-- construct a table of the proper divisor sums
local pds = {}
pds[ 1 ] = 0
for i = 2, maxNumber do pds[ i ] = 1 end
for i = 2, maxNumber do
for j = i + i, maxNumber, i do pds[ j ] = pds[ j ] + i end
end
-- classify the numbers
for n = 1, maxNumber do
local pdSum = pds[ n ]
if pdSum < n then
deficientCount = deficientCount + 1
elseif pdSum == n then
perfectCount = perfectCount + 1
else -- pdSum > n
abundantCount = abundantCount + 1
end
end
io.write( "abundant ", abundantCount, "\n" )
io.write( "deficient ", deficientCount, "\n" )
io.write( "perfect ", perfectCount, "\n" )
end
</syntaxhighlight>
{{out}}
<pre>
abundant 4953
deficient 15043
perfect 4
</pre>
 
=={{header|MAD}}==
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
DIMENSION P(20000)
MAX = 20000
Line 3,175 ⟶ 3,664:
VECTOR VALUES FPER = $I5,S1,7HPERFECT*$
VECTOR VALUES FAB = $I5,S1,8HABUNDANT*$
END OF PROGRAM </langsyntaxhighlight>
{{out}}
<pre>15043 DEFICIENT
Line 3,182 ⟶ 3,671:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple"> classify_number := proc(n::posint);
if evalb(NumberTheory:-SumOfDivisors(n) < 2*n) then
return "Deficient";
Line 3,196 ⟶ 3,685:
num_list := map(classify_number, [seq(1..k)]);
return Statistics:-Tally(num_list)
end proc:</langsyntaxhighlight>
 
{{out}}<pre>["Perfect" = 4, "Abundant" = 4953, "Deficient" = 15043]</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">classify[n_Integer] := Sign[Total[Most@Divisors@n] - n]
 
StringJoin[
Line 3,207 ⟶ 3,696:
Table[classify[n], {n, 20000}]] /. {-1 -> "deficient: ",
0 -> " perfect: ", 1 -> " abundant: "}] /.
n_Integer :> ToString[n]]</langsyntaxhighlight>
 
{{out}}<pre>deficient: 15043 perfect: 4 abundant: 4953</pre>
 
=={{header|MatLab}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
abundant=0; deficient=0; perfect=0; p=[];
for N=2:20000
Line 3,227 ⟶ 3,716:
end
disp(table([deficient;perfect;abundant],'RowNames',{'Deficient','Perfect','Abundant'},'VariableNames',{'Quantities'}))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,236 ⟶ 3,725:
Perfect 4
Abundant 4953
</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Given a number it returns wether it is perfect, deficient or abundant */
number_class(n):=if divsum(n)-n=n then "perfect" else if divsum(n)-n<n then "deficient" else if divsum(n)-n>n then "abundant"$
 
/* Function that displays the number of each kind below n */
classification_count(n):=block(makelist(number_class(i),i,1,n),
[[length(sublist(%%,lambda([x],x="deficient")))," deficient"],[length(sublist(%%,lambda([x],x="perfect")))," perfect"],[length(sublist(%%,lambda([x],x="abundant")))," abundant"]])$
 
/* Test case */
classification_count(20000);
</syntaxhighlight>
{{out}}
<pre>
[[15043," deficient"],[4," perfect"],[4953," abundant"]]
</pre>
 
=={{header|MiniScript}}==
{{Trans|Lua|Summing the factors using a table}}
<syntaxhighlight lang="miniscript">
// classify the numbers 1 : 20 000 as abudant, deficient or perfect
abundantCount = 0
deficientCount = 0
perfectCount = 0
maxNumber = 20000
// construct a table of the proper divisor sums
pds = [0] * ( maxNumber + 1 )
pds[ 1 ] = 0
for i in range( 2, maxNumber )
pds[ i ] = 1
end for
for i in range( 2, maxNumber )
for j in range( i + i, maxNumber, i )
pds[ j ] = pds[ j ] + i
end for
end for
// classify the numbers
for n in range( 1, maxNumber )
pdSum = pds[ n ]
if pdSum < n then
deficientCount = deficientCount + 1
else if pdSum == n then
perfectCount = perfectCount + 1
else // pdSum > n
abundantCount = abundantCount + 1
end if
end for
print "abundant " + abundantCount
print "deficient " + deficientCount
print "perfect " + perfectCount</syntaxhighlight>
{{out}}
<pre>
abundant 4953
deficient 15043
perfect 4
</pre>
 
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">fun proper
(number, count, limit, remainder, results) where (count > limit) = rev results
| (number, count, limit, remainder, results) =
Line 3,264 ⟶ 3,810:
print "Perfect numbers between 1 and 20000: ";
println ` fold (op +, 0) ` map ((fn n = if n then 1 else 0) o is_perfect) one_to_20000;
</syntaxhighlight>
</lang>
Output
<pre>
Line 3,273 ⟶ 3,819:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE ADP;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 3,319 ⟶ 3,865:
WriteString(buf);
ReadChar
END ADP.</langsyntaxhighlight>
 
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
<lang NewLisp>
;;; The list (1 .. n-1) of integers is generated
;;; then each non-divisor of n is replaced by 0
Line 3,344 ⟶ 3,890:
;;; Running:
(println (count-types 20000))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,352 ⟶ 3,898:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">
proc sumProperDivisors(number: int) : int =
if number < 2 : return 0
Line 3,377 ⟶ 3,923:
echo " Perfect = " , perfect
echo " Abundant = " , abundant
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,390 ⟶ 3,936:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: mapping
 
Integer method: properDivs -- []
Line 3,407 ⟶ 3,953:
"Perfects :" . perfect .cr
"Abundant :" . .cr
; </langsyntaxhighlight>
 
{{out}}
Line 3,418 ⟶ 3,964:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">classify(k)=
{
my(v=[0,0,0],t);
Line 3,427 ⟶ 3,973:
v;
}
classify(20000)</langsyntaxhighlight>
{{out}}
<pre>%1 = [15043, 4, 4953]</pre>
 
=={{header|Pascal}}==
==={{header|Free Pascal}}===
using the slightly modified http://rosettacode.org/wiki/Amicable_pairs#Alternative
{{libheader|PrimTrial}}
<lang pascal>program AmicablePairs;
search for "UNIT for prime decomposition".
{find amicable pairs in a limited region 2..MAX
<syntaxhighlight lang="pascal">program KindOfN; //[deficient,perfect,abundant]
beware that >both< numbers must be smaller than MAX
there are 455 amicable pairs up to 524*1000*1000
correct up to
#437 460122410
}
//optimized for freepascal 2.6.4 32-Bit
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$COPERATORS ON}{$CODEALIGN proc=16}
{$OPTIMIZATION ON,peephole,cse,asmcse,regvar}
{$CODEALIGN loop=1,proc=8}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
{$IFDEF WINDOWS} {$APPTYPE CONSOLE}{$ENDIF}
 
uses
sysutils;,PrimeDecomp // limited to 1.2e11
{$IFDEF WINDOWS},Windows{$ENDIF}
const
MAX = 20000;
//alternative copy and paste PrimeDecomp.inc for TIO.RUN
//{$IFDEF UNIX} MAX = 524*1000*1000;{$ELSE}MAX = 499*1000*1000;{$ENDIF}
{$I PrimeDecomp.inc}
type
tKindIdx = 0..2;//[deficient,perfect,abundant];
tValue = LongWord;
tKind = array[tKindIdx] of Uint64;
tpValue = ^tValue;
tPower = array[0..31] of tValue;
tIndex = record
idxI,
idxS : tValue;
end;
tdpa = array[0..2] of LongWord;
var
power : tPower;
PowerFac : tPower;
DivSumField : array[0..MAX] of tValue;
Indices : array[0..511] of tIndex;
DpaCnt : tdpa;
 
procedure InitGetKind(Limit:Uint64);
var
pPrimeDecomp :tpPrimeFac;
i : LongInt;
SumOfKind : tKind;
begin
n: NativeUInt;
DivSumField[0]:= 0;
c: NativeInt;
For i := 1 to MAX do
T0:Int64;
DivSumField[i]:= 1;
Begin
end;
writeln('Limit: ',LIMIT);
 
T0 := GetTickCount64;
procedure ProperDivs(n: tValue);
fillchar(SumOfKind,SizeOf(SumOfKind),#0);
//Only for output, normally a factorication would do
n := 1;
var
Init_Sieve(n);
su,so : string;
i,q : tValue;
begin
su:= '1';
so:= '';
i := 2;
while i*i <= n do
begin
q := n div i;
IF q*i -n = 0 then
begin
su:= su+','+IntToStr(i);
IF q <> i then
so:= ','+IntToStr(q)+so;
end;
inc(i);
end;
writeln(' [',su+so,']');
end;
 
procedure AmPairOutput(cnt:tValue);
var
i : tValue;
r : double;
begin
r := 1.0;
For i := 0 to cnt-1 do
with Indices[i] do
begin
writeln(i+1:4,IdxI:12,IDxS:12,' ratio ',IdxS/IDxI:10:7);
if r < IdxS/IDxI then
r := IdxS/IDxI;
IF cnt < 20 then
begin
ProperDivs(IdxI);
ProperDivs(IdxS);
end;
end;
writeln(' max ratio ',r:10:4);
end;
 
function Check:tValue;
var
i,s,n : tValue;
begin
fillchar(DpaCnt,SizeOf(dpaCnt),#0);
n := 0;
For i := 1 to MAX do
begin
//s = sum of proper divs (I) == sum of divs (I) - I
s := DivSumField[i]-i;
IF (s <=MAX) AND (s>i) then
begin
IF DivSumField[s]-s = i then
begin
With indices[n] do
begin
idxI := i;
idxS := s;
end;
inc(n);
end;
end;
inc(DpaCnt[Ord(s>=i)-Ord(s<=i)+1]);
end;
result := n;
end;
 
Procedure CalcPotfactor(prim:tValue);
//PowerFac[k] = (prim^(k+1)-1)/(prim-1) == Sum (i=1..k) prim^i
var
k: tValue;
Pot, //== prim^k
PFac : Int64;
begin
Pot := prim;
PFac := 1;
For k := 0 to High(PowerFac) do
begin
PFac := PFac+Pot;
IF (POT > MAX) then
BREAK;
PowerFac[k] := PFac;
Pot := Pot*prim;
end;
end;
 
procedure InitPW(prim:tValue);
begin
fillchar(power,SizeOf(power),#0);
CalcPotfactor(prim);
end;
 
function NextPotCnt(p: tValue):tValue;inline;
//return the first power <> 0
//power == n to base prim
var
i : tValue;
begin
result := 0;
repeat
i pPrimeDecomp:= power[result]GetNextPrimeDecomp;
c := pPrimeDecomp^.pfSumOfDivs-2*n;
Inc(i);
c := ORD(c>0)-ORD(c<0)+1;//sgn(c)+1
IF i < p then
inc(SumOfKind[c]);
BREAK
elseinc(n);
until n begin> LIMIT;
iT0 := 0GetTickCount64-T0;
writeln('deficient: ',SumOfKind[0]);
power[result] := 0;
writeln('abundant: ',SumOfKind[2]);
inc(result);
writeln('perfect: ',SumOfKind[1]);
end;
writeln('runtime ',T0/1000:0:3,' s');
until false;
writeln;
power[result] := i;
end;
 
Begin
function Sieve(prim: tValue):tValue;
InitSmallPrimes; //using PrimeDecomp.inc
//simple version
GetKind(20000);
var
GetKind(10*1000*1000);
actNumber : tValue;
GetKind(524*1000*1000);
begin
end.</syntaxhighlight>{{out|@TIO.RUN}}
while prim <= MAX do
<pre>Limit: 20000
begin
deficient: 15043
InitPW(prim);
abundant: 4953
//actNumber = actual number = n*prim
perfect: 4
//power == n to base prim
runtime 0.003 s
actNumber := prim;
while actNumber < MAX do
begin
DivSumField[actNumber] := DivSumField[actNumber] *PowerFac[NextPotCnt(prim)];
inc(actNumber,prim);
end;
//next prime
repeat
inc(prim);
until (DivSumField[prim] = 1);
end;
result := prim;
end;
 
Limit: 1000000
var
deficient: 752451
T2,T1,T0: TDatetime;
abundant: 247545
APcnt: tValue;
perfect: 4
runtime 0.052 s
 
Limit: 524000000
begin
deficient: 394250308
T0:= time;
abundant: 129749687
Init;
perfect: 5
Sieve(2);
runtime 32.987 s
T1:= time;
APCnt := Check;
T2:= time;
//AmPairOutput(APCnt);
writeln(Max:10,' upper limit');
writeln(DpaCnt[0]:10,' deficient');
writeln(DpaCnt[1]:10,' perfect');
writeln(DpaCnt[2]:10,' abundant');
writeln(DpaCnt[2]/Max:14:10,' ratio abundant/upper Limit ');
writeln(DpaCnt[0]/Max:14:10,' ratio abundant/upper Limit ');
writeln(DpaCnt[2]/DpaCnt[0]:14:10,' ratio abundant/deficient ');
writeln('Time to calc sum of divs ',FormatDateTime('HH:NN:SS.ZZZ' ,T1-T0));
writeln('Time to find amicable pairs ',FormatDateTime('HH:NN:SS.ZZZ' ,T2-T1));
{$IFNDEF UNIX}
readln;
{$ENDIF}
end.
</lang>
output
<pre>
20000 upper limit
15043 deficient
4 perfect
4953 abundant
0.2476500000 ratio abundant/upper Limit
0.7521500000 ratio abundant/upper Limit
0.3292561324 ratio abundant/deficient
Time to calc sum of divs 00:00:00.000
Time to find amicable pairs 00:00:00.000
 
Real time: 33.203 s User time: 32.881 s Sys. time: 0.048 s CPU share: 99.17 %
...
524000000 upper limit
394250308 deficient
5 perfect
129749687 abundant
0.2476139065 ratio abundant/upper Limit
0.7523860840 ratio abundant/upper Limit
0.3291048463 ratio abundant/deficient
Time to calc sum of divs 00:00:12.597
Time to find amicable pairs 00:00:04.064
</pre>
 
Line 3,678 ⟶ 4,057:
1 is classified as a [[wp:Deficient_number|deficient number]], 6 is a [[wp:Perfect_number|perfect number]], 12 is an [[wp:Abundant_number|abundant number]]. As per task spec, also showing the totals for the first 20,000 numbers.
 
<langsyntaxhighlight lang="perl">use ntheory qw/divisor_sum/;
my @type = <Perfect Abundant Deficient>;
say join "\n", map { sprintf "%2d %s", $_, $type[divisor_sum($_)-$_ <=> $_] } 1..12;
my %h;
$h{divisor_sum($_)-$_ <=> $_}++ for 1..20000;
say "Perfect: $h{0} Deficient: $h{-1} Abundant: $h{1}";</langsyntaxhighlight>
{{out}}
<pre> 1 Deficient
Line 3,702 ⟶ 4,081:
===Not using a module===
Everything as above, but done more slowly with <code>div_sum</code> providing sum of proper divisors.
<langsyntaxhighlight lang="perl">sub div_sum {
my($n) = @_;
my $sum = 0;
Line 3,713 ⟶ 4,092:
my %h;
$h{div_sum($_) <=> $_}++ for 1..20000;
say "Perfect: $h{0} Deficient: $h{-1} Abundant: $h{1}";</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">deficient</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">perfect</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abundant</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">N</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: #000000;">20000</span> <span style="color: #008080;">do</span>
Line 3,729 ⟶ 4,108:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"deficient:%d, perfect:%d, abundant:%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">deficient</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">perfect</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">abundant</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
deficient:15043, perfect:4, abundant:4953
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
Classes = new_map([deficient=0,perfect=0,abundant=0]),
foreach(N in 1..20_000)
C = classify(N),
Classes.put(C,Classes.get(C)+1)
end,
println(Classes),
nl.
 
% Classify a number N
classify(N) = Class =>
S = sum_divisors(N),
if S < N then
Class1 = deficient
elseif S = N then
Class1 = perfect
elseif S > N then
Class1 = abundant
end,
Class = Class1.
 
% Alternative (slightly slower) approach.
classify2(N,S) = C, S < N => C = deficient.
classify2(N,S) = C, S == N => C = perfect.
classify2(N,S) = C, S > N => C = abundant.
 
% Sum of divisors
sum_divisors(N) = Sum =>
sum_divisors(2,N,cond(N>1,1,0),Sum).
 
% Part 0: base case
sum_divisors(I,N,Sum0,Sum), I > floor(sqrt(N)) =>
Sum = Sum0.
 
% Part 1: I is a divisor of N
sum_divisors(I,N,Sum0,Sum), N mod I == 0 =>
Sum1 = Sum0 + I,
(I != N div I ->
Sum2 = Sum1 + N div I
;
Sum2 = Sum1
),
sum_divisors(I+1,N,Sum2,Sum).
 
% Part 2: I is not a divisor of N.
sum_divisors(I,N,Sum0,Sum) =>
sum_divisors(I+1,N,Sum0,Sum).
</syntaxhighlight>
 
{{out}}
<pre>(map)[perfect = 4,deficient = 15043,abundant = 4953]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de accud (Var Key)
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
Line 3,777 ⟶ 4,209:
((> @@ I) (inc 'A)) ) )
(println D P A) ) )
(bye)</langsyntaxhighlight>
{{Output}}
<pre>
Line 3,785 ⟶ 4,217:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source xref;
apd: Proc Options(main);
p9a=time();
Line 3,840 ⟶ 4,272:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre>In the range 1 - 20000
Line 3,850 ⟶ 4,282:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="pli">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 3,892 ⟶ 4,324:
CALL PRINT(.(' ABUNDANT',13,10,'$'));
CALL EXIT;
EOF</langsyntaxhighlight>
{{out}}
<pre>15043 DEFICIENT
Line 3,900 ⟶ 4,332:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-ProperDivisorSum ( [int]$N )
{
Line 3,934 ⟶ 4,366:
"Perfect : $Perfect"
"Abundant : $Abundant"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,944 ⟶ 4,376:
===As a single function===
Using the <code>Get-ProperDivisorSum</code> as a helper function in an advanced function:
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-NumberClassification
{
Line 4,001 ⟶ 4,433:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..20000 | Get-NumberClassification
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,015 ⟶ 4,447:
 
=={{header|Processing}}==
<langsyntaxhighlight lang="processing">void setup() {
int deficient = 0, perfect = 0, abundant = 0;
for (int i = 1; i <= 20000; i++) {
Line 4,040 ⟶ 4,472:
}
return sum;
}</langsyntaxhighlight>
{{out}}
<pre>Deficient numbers less than 20000: 15043
Line 4,047 ⟶ 4,479:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
proper_divisors(1, []) :- !.
proper_divisors(N, [1|L]) :-
Line 4,090 ⟶ 4,522:
[LD, LA, LP]),
format("took ~f seconds~n", [Dur]).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,101 ⟶ 4,533:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
 
Line 4,138 ⟶ 4,570:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,152 ⟶ 4,584:
===Python: Counter===
Importing [[Proper_divisors#Python:_From_prime_factors|Proper divisors from prime factors]]:
<langsyntaxhighlight lang="python">>>> from proper_divisors import proper_divs
>>> from collections import Counter
>>>
Line 4,166 ⟶ 4,598:
>>> classes.most_common()
[('deficient', 15043), ('abundant', 4953), ('perfect', 4)]
>>> </langsyntaxhighlight>
 
{{out}}
Line 4,179 ⟶ 4,611:
{{Works with|Python|3.7}}
In terms of a single fold:
<langsyntaxhighlight lang="python">'''Abundant, deficient and perfect number classifications'''
 
from itertools import accumulate, chain, groupby, product
Line 4,287 ⟶ 4,719:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
 
and the main function could be rewritten in terms of an nthArrow abstraction:
 
<langsyntaxhighlight lang="python"># nthArrow :: (a -> b) -> Tuple -> Int -> Tuple
def nthArrow(f):
'''A simple function lifted to one which applies to a
Line 4,301 ⟶ 4,733:
x if m != i else f(x) for i, x in enumerate(v)
]
return lambda tpl: lambda n: tuple(go(tpl, n))</langsyntaxhighlight>
 
as something like:
 
<langsyntaxhighlight lang="python"># deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int)
def deficientPerfectAbundantCountsUpTo(n):
'''Counts of deficient, perfect, and abundant
Line 4,317 ⟶ 4,749:
)
)
return reduce(go, range(1, 1 + n), (0, 0, 0))</langsyntaxhighlight>
 
{{Out}}
Line 4,326 ⟶ 4,758:
 
=== The Simple Way ===
<langsyntaxhighlight lang="python">pn = 0
an = 0
dn = 0
Line 4,345 ⟶ 4,777:
print(str(pn) + " Perfect Numbers")
print(str(an) + " Abundant Numbers")
print(str(dn) + " Deficient Numbers")</langsyntaxhighlight>
 
{{Out}}
Line 4,359 ⟶ 4,791:
:Initialize the sum to 1 and start checking factors from 2 and up, which cuts one iteration from each factor checking loop, (a 19,999 iteration savings).<br>
Resulting optimized code is thirty five times faster than the simplified code, and not nearly as complicated as the ''Counter'' or ''Reduce'' methods (as this optimized method requires no imports, other than ''time'' for the performance comparison to ''the simple way'').
<langsyntaxhighlight lang="python">from time import time
st = time()
pn, an, dn = 0, 0, 0
Line 4,397 ⟶ 4,829:
print(str(dn) + " Deficient Numbers")
print(et2 * 1000, "ms\n")
print (et1 / et2,"times faster")</langsyntaxhighlight>
{{out|Output @ Tio.run using Python 3 (PyPy)}}
<pre>4 Perfect Numbers
Line 4,416 ⟶ 4,848:
<code>dpa</code> returns 0 if n is deficient, 1 if n is perfect and 2 if n is abundant.
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 swap witheach + ] is sum ( [ --> n )
 
[ factors -1 pluck
Line 4,433 ⟶ 4,865:
say "Deficient = " echo cr
say " Perfect = " echo cr
say " Abundant = " echo cr</langsyntaxhighlight>
 
{{out}}
Line 4,445 ⟶ 4,877:
{{Works with|R|3.3.2 and above}}
 
<syntaxhighlight lang="r">
<lang r>
# Abundant, deficient and perfect number classifications. 12/10/16 aev
require(numbers);
Line 4,460 ⟶ 4,892:
}
propdivcls(20000);
</langsyntaxhighlight>
 
{{Output}}
Line 4,477 ⟶ 4,909:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
(require math)
(define (proper-divisors n) (drop-right (divisors n) 1))
Line 4,490 ⟶ 4,922:
(hash-set! t c (add1 (hash-ref t c 0))))
(printf "The range between 1 and ~a has:\n" N)
(for ([c classes]) (printf " ~a ~a numbers\n" (hash-ref t c 0) c)))</langsyntaxhighlight>
 
{{out}}
Line 4,503 ⟶ 4,935:
(formerly Perl 6)
{{Works with|rakudo|2018.12}}
<syntaxhighlight lang="raku" perl6line>sub propdivsum (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
Line 4,511 ⟶ 4,943:
}
 
say bag (1..20000).map: { propdivsum($_) <=> $_ }</langsyntaxhighlight>
{{out}}
<pre>Bag(Less(15043), More(4953), Same(4))</pre>
Line 4,517 ⟶ 4,949:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX program counts the number of abundant/deficient/perfect numbers within a range.*/
parse arg low high . /*obtain optional arguments from the CL*/
high=word(high low 20000,1); low= word(low 1,1) /*obtain the LOW and HIGH values.*/
Line 4,539 ⟶ 4,971:
end /*k*/ /* [↑] % is the REXX integer division*/
if k*k==x then return s + k /*Was X a square? If so, add √ x */
return s /*return (sigma) sum of the divisors. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 4,555 ⟶ 4,987:
" 100k " " " '''20%''' "
" 1m " " " '''30%''' "
<langsyntaxhighlight lang="rexx">/*REXX program counts the number of abundant/deficient/perfect numbers within a range.*/
parse arg low high . /*obtain optional arguments from the CL*/
high=word(high low 20000,1); low=word(low 1, 1) /*obtain the LOW and HIGH values.*/
Line 4,579 ⟶ 5,011:
end /*k*/ /* [↑] % is the REXX integer division*/
if r*r==x then return s - k /*Was X a square? If so, subtract √ x */
return s /*return (sigma) sum of the divisors. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}}
 
Line 4,586 ⟶ 5,018:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX */
Call time 'R'
cnt.=0
Line 4,636 ⟶ 5,068:
sum=sum+word(list,i)
End
Return sum</langsyntaxhighlight>
{{out}}
<pre>In the range 1 - 20000
Line 4,645 ⟶ 5,077:
 
=={{header|Ring}}==
The following classifies the first few numbers of each type.
<lang ring>
<syntaxhighlight lang="ring">
n = 30
perfect(n)
Line 4,660 ⟶ 5,093:
else see " is a abundant number" + nl ok
next
</syntaxhighlight>
</lang>
 
===Task using modulo/division===
{{Trans|Lua|Summing the factors using modulo/division}}
<syntaxhighlight lang="ring">
a = 0
d = 0
p = 0
for n = 1 to 20000
Pn = sumDivs(n)
if Pn > n a = a + 1 ok
if Pn < n d = d + 1 ok
if Pn = n p = p + 1 ok
next
see "Abundant : " + a + nl
see "Deficient: " + d + nl
see "Perfect : " + p + nl
 
func sumDivs (n)
if n < 2 return 0
else
sum = 1
sr = sqrt(n)
for d = 2 to sr
if n % d = 0
sum = sum + d
if d != sr sum = sum + n / d ok
ok
next
return sum
ok
</syntaxhighlight>
 
{{out}}
<pre>
Abundant : 4953
Deficient: 15043
Perfect : 4
</pre>
 
===Task using a table===
{{Trans|Lus|Summiing the factors using a table}}
<syntaxhighlight lang="ring">
maxNumber = 20000
abundantCount = 0
deficientCount = 0
perfectCount = 0
 
pds = list( maxNumber )
pds[ 1 ] = 0
for i = 2 to maxNumber pds[ i ] = 1 next
for i = 2 to maxNumber
for j = i + i to maxNumber step i pds[ j ] = pds[ j ] + i next
next
for n = 1 to maxNumber
pdSum = pds[ n ]
if pdSum < n
deficientCount = deficientCount + 1
but pdSum = n
perfectCount = perfectCount + 1
else # pdSum > n
abundantCount = abundantCount + 1
ok
next
 
see "Abundant : " + abundantCount + nl
see "Deficient: " + deficientCount + nl
see "Perfect : " + perfectCount + nl
</syntaxhighlight>
 
{{out}}
<pre>
Abundant : 4953
Deficient: 15043
Perfect : 4
</pre>
 
=={{header|RPL}}==
{{works with|HP|49}}
≪ [1 0 0]
2 20000 '''FOR''' n
n DIVIS REVLIST TAIL <span style="color:grey">@ get the list of divisors of n excluding n</span>
0. + <span style="color:grey">@ avoid ∑LIST and SIGN errors when n is prime </span>
∑LIST n - SIGN 2 + <span style="color:grey">@ turn P(n)-n into 1, 2 or 3</span>
DUP2 GET 1 + PUT <span style="color:grey">@ increment appropriate array element</span>
'''NEXT'''
≫ '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: [15042 4 4953]
</pre>
 
=={{header|Ruby}}==
{{Works with|ruby|2.7}}
With [[proper_divisors#Ruby]] in place:
<langsyntaxhighlight lang="ruby">res = (1 .. 20_000).map{|n| n.proper_divisors.sum <=> n }.tally
puts "Deficient: #{res[-1]} Perfect: #{res[0]} Abundant: #{res[1]}"
</syntaxhighlight>
</lang>
{{out}}<pre>
Deficient: 15043 Perfect: 4 Abundant: 4953
Line 4,675 ⟶ 5,198:
 
With [[proper_divisors#Rust]] in place:
<langsyntaxhighlight lang="rust">fn main() {
// deficient starts at 1 because 1 is deficient but proper_divisors returns
// and empty Vec
Line 4,694 ⟶ 5,217:
deficient, perfect, abundant);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,704 ⟶ 5,227:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
def classifier(i: Int) = properDivisors(i).sum compare i
val groups = (1 to 20000).groupBy( classifier )
println("Deficient: " + groups(-1).length)
println("Abundant: " + groups(1).length)
println("Perfect: " + groups(0).length + " (" + groups(0).mkString(",") + ")")</langsyntaxhighlight>
{{out}}
<pre>Deficient: 15043
Line 4,716 ⟶ 5,239:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">
(define (classify n)
(define (sum_of_factors x)
Line 4,741 ⟶ 5,264:
((equal? (classify n) 1) (begin (set! n_abundant (+ 1 n_abundant)) (count (- n 1))))
((equal? (classify n) -1) (begin (set! n_deficient (+ 1 n_deficient)) (count (- n 1))))))
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: sumProperDivisors (in integer: number) is func
Line 4,782 ⟶ 5,305:
writeln("Perfect: " <& perfect);
writeln("Abundant: " <& abundant);
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,790 ⟶ 5,313:
Abundant: 4953
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program classifications;
P := properdivisorsums(20000);
 
print("Deficient:", #[n : n in [1..#P] | P(n) < n]);
print(" Perfect:", #[n : n in [1..#P] | P(n) = n]);
print(" Abundant:", #[n : n in [1..#P] | P(n) > n]);
 
proc properdivisorsums(n);
p := [0];
loop for i in [1..n] do
loop for j in [i*2, i*3..n] do
p(j) +:= i;
end loop;
end loop;
return p;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>Deficient: 15043
Perfect: 4
Abundant: 4953</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func propdivsum(n) { n.sigma - n }
 
var h = Hash()
{|i| ++(h{propdivsum(i) <=> i} := 0) } << 1..20000
say "Perfect: #{h{0}} Deficient: #{h{-1}} Abundant: #{h{1}}"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,804 ⟶ 5,350:
=={{header|Swift}}==
{{trans|C}}
<langsyntaxhighlight lang="swift">var deficients = 0 // sumPd < n
var perfects = 0 // sumPd = n
var abundants = 0 // sumPd > n
Line 4,844 ⟶ 5,390:
}
 
println("There are \(deficients) deficient, \(perfects) perfect and \(abundants) abundant integers from 1 to 20000.")</langsyntaxhighlight>
{{out}}<pre>There are 15043 deficient, 4 perfect and 4953 abundant integers from 1 to 20000.</pre>
 
=={{header|Tcl}}==
 
<langsyntaxhighlight Tcllang="tcl">proc ProperDivisors {n} {
if {$n == 1} {return 0}
set divs 1
Line 4,892 ⟶ 5,438:
foreach {kind count} [lsort -stride 2 -index 1 -integer $classes] {
puts "$kind: $count"
}</langsyntaxhighlight>
 
{{out}}
Line 4,934 ⟶ 5,480:
=={{header|uBasic/4tH}}==
This is about the limit of what is feasible with uBasic/4tH performance wise, since a full run takes over 5 minutes.
<syntaxhighlight lang="text">P = 0 : D = 0 : A = 0
 
For n= 1 to 20000
Line 4,984 ⟶ 5,530:
 
If (b@ > 1) c@ = c@ * (b@+1)
Return (c@)</langsyntaxhighlight>
{{out}}
<pre>Perfect: 4 Deficient: 15043 Abundant: 4953
Line 4,992 ⟶ 5,538:
=={{header|Vala}}==
{{trans|C}}
<langsyntaxhighlight lang="vala">enum Classification {
DEFICIENT,
PERFECT,
Line 5,026 ⟶ 5,572:
print(@" $(count_list[Classification.PERFECT]) perfect,");
print(@" $(count_list[Classification.ABUNDANT]) abundant numbers between 1 and 20000.\n");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,033 ⟶ 5,579:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang VB>
Option Explicit
Line 5,065 ⟶ 5,611:
If n Mod j = 0 Then SumPropers = j + SumPropers
Next
End Function</langsyntaxhighlight>
{{out}}
<pre>Execution Time : 2,6875 seconds.
Line 5,074 ⟶ 5,620:
 
=={{header|VBScript}}==
<langsyntaxhighlight VBScriptlang="vbscript">Deficient = 0
Perfect = 0
Abundant = 0
Line 5,096 ⟶ 5,642:
WScript.Echo "Deficient = " & Deficient & vbCrLf &_
"Perfect = " & Perfect & vbCrLf &_
"Abundant = " & Abundant</langsyntaxhighlight>
{{out}}
<pre>Deficient = 15043
Line 5,104 ⟶ 5,650:
=={{header|Visual Basic .NET}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function SumProperDivisors(number As Integer) As Integer
Line 5,136 ⟶ 5,682:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>The classification of the numbers from 1 to 20,000 is as follows :
Line 5,143 ⟶ 5,689:
Perfect = 4
Abundant = 4953</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn p_fac_sum(i int) int {
mut sum := 0
for p := 1; p <= i/2; p++ {
if i%p == 0 {
sum += p
}
}
return sum
}
fn main() {
mut d := 0
mut a := 0
mut p := 0
for i := 1; i <= 20000; i++ {
j := p_fac_sum(i)
if j < i {
d++
} else if j == i {
p++
} else {
a++
}
}
println("There are $d deficient numbers between 1 and 20000")
println("There are $a abundant numbers between 1 and 20000")
println("There are $p perfect numbers between 1 and 20000")
}</syntaxhighlight>
 
{{out}}
<pre>
There are 15043 deficient numbers between 1 and 20000
There are 4953 abundant numbers between 1 and 20000
There are 4 perfect numbers between 1 and 20000
</pre>
 
=={{header|VTL-2}}==
<syntaxhighlight lang="vtl2">10 M=20000
20 I=1
30 :I)=0
40 I=I+1
50 #=M>I*30
60 I=1
70 J=I*2
80 :J)=:J)+I
90 J=J+I
100 #=M>J*80
110 I=I+1
120 #=M/2>I*70
130 D=0
140 P=0
150 A=0
160 I=1
170 #=:I)<I*230
180 #=:I)=I*210
190 A=A+1
200 #=240
210 P=P+1
220 #=240
230 D=D+1
240 I=I+1
250 #=M>I*170
260 ?=D
270 ?=" deficient"
280 ?=P
290 ?=" perfect"
300 ?=A
310 ?=" abundant"</syntaxhighlight>
{{out}}
<pre>15043 deficient
4 perfect
4953 abundant</pre>
 
=={{header|Wren}}==
===Using modulo/division===
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int, Nums
 
var d = 0
Line 5,163 ⟶ 5,785:
System.print("There are %(d) deficient numbers between 1 and 20000")
System.print("There are %(a) abundant numbers between 1 and 20000")
System.print("There are %(p) perfect numbers between 1 and 20000")</langsyntaxhighlight>
 
{{out}}
Line 5,170 ⟶ 5,792:
There are 4953 abundant numbers between 1 and 20000
There are 4 perfect numbers between 1 and 20000
</pre>
 
===Using a table===
Alternative version, computing a table of divisor sums.
{{Trans|Lua|Summing the factors using a table}}
 
<syntaxhighlight lang="wren">var maxNumber = 20000
var abundantCount = 0
var deficientCount = 0
var perfectCount = 0
 
var pds = []
pds.add(0) // element 0
pds.add(0) // element 1
for (i in 2..maxNumber) {
pds.add(1)
}
for (i in 2..maxNumber) {
var j = i + i
while (j <= maxNumber) {
pds[j] = pds[j] + i
j = j + i
}
}
for (n in 1..maxNumber) {
var pdSum = pds[n]
if (pdSum < n) {
deficientCount = deficientCount + 1
} else if (pdSum == n) {
perfectCount = perfectCount + 1
} else { // pdSum > n
abundantCount = abundantCount + 1
}
}
 
System.print("Abundant : %(abundantCount)")
System.print("Deficient: %(deficientCount)")
System.print("Perfect : %(perfectCount)")</syntaxhighlight>
 
{{out}}
<pre>
Abundant : 4953
Deficient: 15043
Perfect : 4
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">int CntD, CntP, CntA, Num, Div, Sum;
[CntD:= 0; CntP:= 0; CntA:= 0;
for Num:= 1 to 20000 do
[Sum:= if Num = 1 then 0 else 1;
for Div:= 2 to Num-1 do
if rem(Num/Div) = 0 then
Sum:= Sum + Div;
case of
Sum < Num: CntD:= CntD+1;
Sum > Num: CntA:= CntA+1
other CntP:= CntP+1;
];
Text(0, "Deficient: "); IntOut(0, CntD); CrLf(0);
Text(0, "Perfect: "); IntOut(0, CntP); CrLf(0);
Text(0, "Abundant: "); IntOut(0, CntA); CrLf(0);
]</syntaxhighlight>
 
{{out}}
<pre>
Deficient: 15043
Perfect: 4
Abundant: 4953
</pre>
 
=={{header|Yabasic}}==
{{trans|AWK}}
<langsyntaxhighlight Yabasiclang="yabasic">clear screen
 
Deficient = 0
Line 5,208 ⟶ 5,899:
end if
return sum
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) }
fcn classify(n){
Line 5,224 ⟶ 5,915:
abundant :=classified.filter('==(1)).len();
println("Deficient=%d, perfect=%d, abundant=%d".fmt(
classified.len()-perfect-abundant, perfect, abundant));</langsyntaxhighlight>
{{out}}<pre>Deficient=15043, perfect=4, abundant=4953</pre>
 
=={{header|ZX Spectrum Basic}}==
Solution 1:
<langsyntaxhighlight lang="zxbasic"> 10 LET nd=1: LET np=0: LET na=0
20 FOR i=2 TO 20000
30 LET sum=1
Line 5,243 ⟶ 5,934:
130 PRINT "Number deficient: ";nd
140 PRINT "Number perfect: ";np
150 PRINT "Number abundant: ";na</langsyntaxhighlight>
 
Solution 2 (more efficient):
<langsyntaxhighlight lang="zxbasic"> 10 LET abundant=0: LET deficient=0: LET perfect=0
20 FOR j=1 TO 20000
30 GO SUB 120
Line 5,264 ⟶ 5,955:
170 NEXT i
180 LET sump=sum
190 RETURN</langsyntaxhighlight>
2,096

edits