Abundant, deficient and perfect number classifications: Difference between revisions
Abundant, deficient and perfect number classifications (view source)
Revision as of 16:24, 14 March 2024
, 2 months agoAdd ABC
m (→{{header|Picat}}: Added out tag.) |
Not a robot (talk | contribs) (Add ABC) |
||
(37 intermediate revisions by 15 users not shown) | |||
Line 28:
=={{header|11l}}==
{{trans|Kotlin}}
<
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)</
{{out}}
<pre>
Line 58:
For maximum compatibility, this program uses only the basic instruction set (S/360)
with 2 ASSIST macros (XDECO,XPRNT).
<
ABUNDEFI CSECT
USING ABUNDEFI,R13 set base register
Line 113:
XDEC DS CL12
REGEQU
END ABUNDEFI</
{{out}}
<pre>
Line 119:
</pre>
=={{header|8086 Assembly}}==
<
cpu 8086
org 100h
Line 199:
db '.....'
snum: db 13,10,'$'
data: equ $</
{{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">
/* 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>
{{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.
<
CARD i,j
Line 732 ⟶ 765:
PrintF(" Perfect: %I%E",perf)
PrintF(" Abudant: %I%E",abud)
RETURN</
{{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]].
<
procedure ADB_Classification is
Line 781 ⟶ 814:
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line("====================");
end ADB_Classification;</
{{out}}
Line 792 ⟶ 825:
=={{header|ALGOL 68}}==
<
INT abundant count := 0;
INT deficient count := 0;
INT perfect count := 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
ELIF pd sum = n THEN
ELSE # pd sum > n #
FI
OD;
print( ( "abundant ", whole( abundant count, 0 ), newline ) );
print( ( "deficient ", whole( deficient count, 0 ), newline ) );
print( ( "perfect ", whole( perfect count, 0 ), newline ) )
END
</syntaxhighlight>
{{out}}
<pre>
abundant 4953
deficient 15043
perfect 4
</pre>
=={{header|ALGOL W}}==
<
integer MAX_NUMBER;
MAX_NUMBER := 20000;
Line 876 ⟶ 884:
write( "Deficient numbers up to 20 000: ", dCount )
end
end.</
{{out}}
<pre>
Line 885 ⟶ 893:
=={{header|AppleScript}}==
<
if (n < 2) then return 0
set sum to 1
Line 917 ⟶ 925:
end task
task()</
{{output}}
<
=={{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 numberClassif.s */
Line 1,378 ⟶ 1,386:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 1,386 ⟶ 1,394:
</pre>
=={{header|Arturo}}==
<
(factors n) -- n
Line 1,402 ⟶ 1,410:
print ["Found" abundant "abundant,"
deficient "deficient and"
perfect "perfect numbers."]</
{{out}}
Line 1,409 ⟶ 1,417:
=={{header|AutoHotkey}}==
<
{
m := A_index
Line 1,461 ⟶ 1,469:
esc::ExitApp
</syntaxhighlight>
{{out}}
<pre>
Line 1,478 ⟶ 1,486:
=={{header|AWK}}==
works with GNU Awk 3.1.5 and with BusyBox v1.21.1
<syntaxhighlight lang="awk">
#!/bin/gawk -f
function sumprop(num, i,sum,root) {
Line 1,515 ⟶ 1,523:
print "Deficient: " deficient
}
</syntaxhighlight>
{{out}}
Line 1,527 ⟶ 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.
<
@echo off
setlocal enabledelayedexpansion
Line 1,561 ⟶ 1,569:
exit /b %sumdivisers%
</syntaxhighlight>
=={{header|BASIC}}==
{{works with|Chipmunk Basic}}
{{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,574 ⟶ 1,586:
90 PRINT "DEFICIENT:";D
100 PRINT "PERFECT:";P
110 PRINT "ABUNDANT:";A</
{{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}}==
<
manifest $( maximum = 20000 $)
Line 1,611 ⟶ 1,811:
writef("Abundant numbers: %N*N", ab)
freevec(p)
$)</
{{out}}
<pre>Deficient numbers: 15043
Line 1,621 ⟶ 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.
<
++\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">:#,_@</
{{out}}
Line 1,632 ⟶ 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.
<
& ( multiples
= prime multiplicity
Line 1,704 ⟶ 1,904:
& clk$:?t3
& out$(flt$(!t3+-1*!t2,2) sec)
);</
Output:
<pre>deficient 15043 perfect 4 abundant 4953
Line 1,712 ⟶ 1,912:
=={{header|C}}==
<syntaxhighlight lang="c">
#include<stdio.h>
#define de 0
Line 1,755 ⟶ 1,955:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,770 ⟶ 1,970:
Third method:
:Uses a loop with a inner Enumerable.Range reaching to i / 2, only adding one divisor at a time.
<
using System.Linq;
Line 1,833 ⟶ 2,033:
deficient = bound - abundant - perfect;
}
}</
{{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,843 ⟶ 2,043:
=={{header|C++}}==
<
#include <algorithm>
#include <vector>
Line 1,875 ⟶ 2,075:
std::cout << "Abundant : " << abundants.size( ) << std::endl ;
return 0 ;
}</
{{out}}
<pre>Deficient : 15043
Line 1,883 ⟶ 2,083:
=={{header|Ceylon}}==
<
function divisors(Integer int) =>
Line 1,895 ⟶ 2,095:
print("perfect: ``counts[equal] else "none"``");
print("abundant: ``counts[larger] else "none"``");
}</
{{out}}
<pre>
Line 1,903 ⟶ 2,103:
=={{header|Clojure}}==
<
[n]
(let [divs (filter #(zero? (mod n %)) (range 1 n))
Line 1,919 ⟶ 2,119:
{:perfect (count (filter #(= % :perfect) classes))
:abundant (count (filter #(= % :abundant) classes))
:deficient (count (filter #(= % :deficient) classes))}))</
Example:
<
;=> {:perfect 4,
; :abundant 4953,
; :deficient 15043}</
=={{header|CLU}}==
<
proper_divisors = proc (max: int) returns (array[int])
divs: array[int] := array[int]$fill(1, max, 0)
Line 1,963 ⟶ 2,163:
stream$putl(po, "Perfect: " || int$unparse(per))
stream$putl(po, "Abundant: " || int$unparse(ab))
end start_up</
{{out}}
<pre>Deficient: 15043
Line 1,971 ⟶ 2,171:
=={{header|Common Lisp}}==
<
(let ((divisor-sum (sum-divisors n)))
(cond ((< divisor-sum n) :deficient)
Line 1,988 ⟶ 2,188:
:count (eq class :perfect) :into perfect
:count (eq class :abundant) :into abundant
:finally (return (values deficient perfect abundant))))</
Output:
Line 1,998 ⟶ 2,198:
=={{header|Cowgol}}==
<
const MAXIMUM := 20000;
Line 2,034 ⟶ 2,234:
print_i16(def); print(" deficient numbers.\n");
print_i16(per); print(" perfect numbers.\n");
print_i16(ab); print(" abundant numbers.\n");</
{{out}}
<pre>15043 deficient numbers.
Line 2,041 ⟶ 2,241:
=={{header|D}}==
<
import std.stdio, std.algorithm, std.range;
Line 2,058 ⟶ 2,258:
//iota(1, 1 + rangeMax).map!classify.hashGroup.writeln;
iota(1, 1 + rangeMax).map!classify.array.sort().group.writeln;
}</
{{out}}
<pre>[Tuple!(Class, uint)(deficient, 15043), Tuple!(Class, uint)(perfect, 4), Tuple!(Class, uint)(abundant, 4953)]</pre>
Line 2,065 ⟶ 2,265:
See [[#Pascal]].
=={{header|Draco}}==
<
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
Line 2,101 ⟶ 2,301:
writeln("Perfect: ", per:5);
writeln("Abundant: ", ab:5)
corp</
{{out}}
<pre>Deficient: 15043
Line 2,111 ⟶ 2,311:
{{trans|C#}}
<
var (a, d, p) = (0, 0, 0)
var sum = Array.Empty(bound + 1, 0)
Line 2,134 ⟶ 2,334:
(abundant: a, deficient: d, perfect: p)
}
func
}
}
}
func Iterator.Sum() {
for x in this
sum += x
}
sum
}
func division(bound) {
var (a, d, p) = (0, 0, 0)
for i in 1..20000 {
Line 2,172 ⟶ 2,374:
out( sieve(20000) )
out( division(20000) )</
{{out}}
Line 2,178 ⟶ 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}}==
<
(lib 'math) ;; sum-divisors function
Line 2,206 ⟶ 2,445:
deficient 15043
perfect 4
</syntaxhighlight>
=={{header|Ela}}==
{{trans|Haskell}}
<
divisors n = filter ((0 ==) << (n `mod`)) [1 .. (n `div` 2)]
Line 2,221 ⟶ 2,460:
printRes "deficient: " LT
printRes "perfect: " EQ
printRes "abundant: " GT</
{{out}}
Line 2,230 ⟶ 2,469:
=={{header|Elena}}==
{{trans|C#}}
ELENA
<
classifyNumbers(int bound, ref int abundant, ref int deficient, ref int perfect)
Line 2,240 ⟶ 2,479:
int[] sum := new int[](bound + 1);
for(int divisor := 1
{
for(int i := divisor + divisor
{
sum[i] := sum[i] + divisor
Line 2,248 ⟶ 2,487:
};
for(int i := 1
{
int t := sum[i];
Line 2,281 ⟶ 2,520:
classifyNumbers(20000, ref abundant, ref deficient, ref perfect);
console.printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect)
}</
{{out}}
<pre>
Line 2,288 ⟶ 2,527:
=={{header|Elixir}}==
<
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
Line 2,306 ⟶ 2,545:
end
end)
IO.puts "Deficient: #{deficient} Perfect: #{perfect} Abundant: #{abundant}"</
{{out}}
Line 2,314 ⟶ 2,553:
=={{header|Erlang}}==
<
-module(properdivs).
-export([divs/1,sumdivs/1,class/1]).
Line 2,346 ⟶ 2,585:
class(D,P,A,Sum,Acc,L) when Acc > Sum ->
class(D+1,P,A,sumdivs(Acc+1),Acc+1,L).
</syntaxhighlight>
{{out}}
Line 2,362 ⟶ 2,601:
===Erlang 2===
The version above is not tail-call recursive, and so cannot classify large ranges. Here is a more optimal solution.
<
-module(proper_divisors).
-export([classify_range/2]).
Line 2,392 ⟶ 2,631:
proper_divisors(I, L, N, A) ->
proper_divisors(I+1, L, N, [N div I, I|A]).
</syntaxhighlight>
{{output}}
<pre>
Line 2,400 ⟶ 2,639:
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="f#">
let mutable a=0
let mutable b=0
Line 2,422 ⟶ 2,661:
printfn "perfect %i"d
printfn "abundant %i"e
</syntaxhighlight>
An immutable solution.
<
let deficient, perfect, abundant = 0,1,2
Line 2,439 ⟶ 2,678:
|> List.zip [ "deficient"; "perfect"; "abundant" ]
|> List.iter (fun (label, count) -> printfn "%s: %d" label count)
</syntaxhighlight>
=={{header|Factor}}==
<
USING: fry math.primes.factors math.ranges ;
: psum ( n -- m ) divisors but-last sum ;
Line 2,451 ⟶ 2,690:
[ +eq+ pcount "Perfect: " write . ]
[ +gt+ pcount "Abundant: " write . ] tri
</syntaxhighlight>
{{out}}
<pre>
Line 2,461 ⟶ 2,700:
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<
: SLOT ( x y -- 0|1|2) OVER OVER < -ROT > - 1+ ;
: CLASSIFY ( n -- n') \ 0 == deficient, 1 == perfect, 2 == abundant
Line 2,486 ⟶ 2,725:
." Perfect : " [ COUNTS 1 CELLS + ]L @ . CR
." Abundant : " [ COUNTS 2 CELLS + ]L @ . CR ;
20000 CLASSIFY-NUMBERS .COUNTS BYE</
{{out}}
<pre>Deficient : 15043
Line 2,503 ⟶ 2,742:
Abundant 4953
<syntaxhighlight 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,542 ⟶ 2,781:
WRITE (6,*) "Abundant ",COUNT(TEST .GT. 0) !Alternatively, make one pass with three counts.
END !Done.
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
' FreeBASIC v1.05.0 win64
Line 2,579 ⟶ 2,818:
Sleep
End
</syntaxhighlight>
{{out}}
Line 2,591 ⟶ 2,830:
=={{header|Frink}}==
<
d = new dict
for n = 1 to 20000
Line 2,603 ⟶ 2,842:
println["Perfect: " + d@0]
println["Abundant: " + d@1]
</syntaxhighlight>
{{out}}
<pre>
Line 2,610 ⟶ 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,659 ⟶ 2,945:
RETURN sum%
ENDFUNC
</syntaxhighlight>
Output is:
Line 2,669 ⟶ 2,955:
=={{header|Go}}==
<
import "fmt"
Line 2,698 ⟶ 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)
}</
{{out}}
Line 2,710 ⟶ 2,996:
=====Solution:=====
Uses the "factorize" closure from [[Factors of an integer]]
<
def n = factors.pop()
def fSum = factors.sum()
Line 2,724 ⟶ 3,010:
map
}
.each { e -> println e }</
{{out}}
<pre>deficient=15043
Line 2,731 ⟶ 3,017:
=={{header|Haskell}}==
<
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
Line 2,743 ⟶ 3,029:
printRes "deficient: " LT
printRes "perfect: " EQ
printRes "abundant: " GT</
{{out}}
<pre>deficient: 15043
Line 2,751 ⟶ 3,037:
Or, a little faster and more directly, as a single fold:
<
import Data.List (group, sort)
Line 2,770 ⟶ 3,056:
main :: IO ()
main = print $ deficientPerfectAbundantCountsUpTo 20000</
{{Out}}
<pre>(15043,4,4953)</pre>
Line 2,777 ⟶ 3,063:
[[Proper divisors#J|Supporting implementation]]:
<
properDivisors=: factors -. ]</
We can subtract the sum of a number's proper divisors from itself to classify the number:
<
1 1 2 1 4 0 6 1 5 2</
Except, we are only concerned with the sign of this difference:
<
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</
Also, we do not care about the individual classification but only about how many numbers fall in each category:
<
15043 4 4953</
So: 15043 deficient, 4 perfect and 4953 abundant numbers in this range.
Line 2,799 ⟶ 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):
<
1 0 _1</
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,806 ⟶ 3,092:
=={{header|Java}}==
{{works with|Java|8}}
<
public class NumberClassifications {
Line 2,832 ⟶ 3,118:
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n != i && n % i == 0).sum();
}
}</
<pre>Deficient: 15043
Line 2,841 ⟶ 3,127:
===ES5===
<
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>' )</
'''Or:'''
<
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>' )</
'''Or:'''
<
var ps = {2:true, 3:true}
next: for (var n=5, i=2; n<=t; n+=i, i=6-i) {
Line 2,901 ⟶ 3,187:
dpa[ds<n ? 0 : ds==n ? 1 : 2]+=1
}
document.write('Deficient:',dpa[0], ', Perfect:',dpa[1], ', Abundant:',dpa[2], '<br>' )</
{{output}}
<pre>Deficient:15043, Perfect:4, Abundant:4953</pre>
Line 2,907 ⟶ 3,193:
===ES6===
{{Trans|Haskell}}
<
'use strict';
Line 2,948 ⟶ 3,234:
.length.toString())
.join('\n');
})();</
{{Out}}
Line 2,954 ⟶ 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]]:
<
def proper_divisors:
. as $n
Line 2,968 ⟶ 3,297:
end)
else empty
end;</
'''The task:'''
<
def classify:
Line 2,977 ⟶ 3,306:
| if . < $n then "deficient" elif . == $n then "perfect" else "abundant" end;
reduce (range(1; 20001) | classify) as $c ({}; .[$c] += 1 )</
{{out}}
<
{"deficient":15043,"perfect":4,"abundant":4953}</
=={{header|Jsish}}==
From Javascript ES5 entry.
<
function classifyDPA(stop:number, start:number=0, step:number=1):array {
var dpa = [1, 0, 0];
Line 2,996 ⟶ 3,325:
var dpa = classifyDPA(20000, 2);
printf('Deficient: %d, Perfect: %d, Abundant: %d\n', dpa[0], dpa[1], dpa[2]);</
{{out}}
Line 3,020 ⟶ 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">
function pcontrib(p::Int64, a::Int64)
n = one(p)
Line 3,038 ⟶ 3,367:
dsum -= n
end
</syntaxhighlight>
Perhaps <code>pcontrib</code> could be made more efficient by caching results to avoid repeated calculations.
Line 3,045 ⟶ 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">
const L = 2*10^4
iclasslabel = ["Deficient", "Perfect", "Abundant"]
Line 3,063 ⟶ 3,392:
println(" ", iclasslabel[i], ", ", iclass[i])
end
</syntaxhighlight>
{{out}}
Line 3,072 ⟶ 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}}
<syntaxhighlight lang="k">
/Classification of numbers into abundant, perfect and deficient
/ numclass.k
Line 3,086 ⟶ 3,435:
`0: ,"Perfect = ", $(#c[1])
`0: ,"Abundant = ", $(#c[2])
</syntaxhighlight>
{{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,092 ⟶ 3,460:
Perfect = 4
Abundant = 4953
</pre>
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<
fun sumProperDivisors(n: Int) =
Line 3,121 ⟶ 3,488:
println("Perfect = $perfect")
println("Abundant = $abundant")
}</
{{out}}
Line 3,133 ⟶ 3,500:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
print "ROSETTA CODE - Abundant, deficient and perfect number classifications"
print
Line 3,183 ⟶ 3,550:
next y
end function
</syntaxhighlight>
{{out}}
<pre>
Line 3,209 ⟶ 3,576:
=={{header|Lua}}==
===Summing the factors using modulo/division===
<syntaxhighlight lang="lua">function sumDivs (n)
if n < 2 then return 0 end
local sum, sr = 1, math.sqrt(n)
Line 3,230 ⟶ 3,598:
print("Abundant:", a)
print("Deficient:", d)
print("Perfect:", p)</
{{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}}==
<
DIMENSION P(20000)
MAX = 20000
Line 3,258 ⟶ 3,664:
VECTOR VALUES FPER = $I5,S1,7HPERFECT*$
VECTOR VALUES FAB = $I5,S1,8HABUNDANT*$
END OF PROGRAM </
{{out}}
<pre>15043 DEFICIENT
Line 3,265 ⟶ 3,671:
=={{header|Maple}}==
<
if evalb(NumberTheory:-SumOfDivisors(n) < 2*n) then
return "Deficient";
Line 3,279 ⟶ 3,685:
num_list := map(classify_number, [seq(1..k)]);
return Statistics:-Tally(num_list)
end proc:</
{{out}}<pre>["Perfect" = 4, "Abundant" = 4953, "Deficient" = 15043]</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
StringJoin[
Line 3,290 ⟶ 3,696:
Table[classify[n], {n, 20000}]] /. {-1 -> "deficient: ",
0 -> " perfect: ", 1 -> " abundant: "}] /.
n_Integer :> ToString[n]]</
{{out}}<pre>deficient: 15043 perfect: 4 abundant: 4953</pre>
=={{header|MatLab}}==
<syntaxhighlight lang="matlab">
abundant=0; deficient=0; perfect=0; p=[];
for N=2:20000
Line 3,310 ⟶ 3,716:
end
disp(table([deficient;perfect;abundant],'RowNames',{'Deficient','Perfect','Abundant'},'VariableNames',{'Quantities'}))
</syntaxhighlight>
{{out}}
<pre>
Line 3,319 ⟶ 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}}===
<
(number, count, limit, remainder, results) where (count > limit) = rev results
| (number, count, limit, remainder, results) =
Line 3,347 ⟶ 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>
Output
<pre>
Line 3,356 ⟶ 3,819:
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 3,402 ⟶ 3,865:
WriteString(buf);
ReadChar
END ADP.</
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
;;; The list (1 .. n-1) of integers is generated
;;; then each non-divisor of n is replaced by 0
Line 3,427 ⟶ 3,890:
;;; Running:
(println (count-types 20000))
</syntaxhighlight>
{{out}}
Line 3,435 ⟶ 3,898:
=={{header|Nim}}==
<
proc sumProperDivisors(number: int) : int =
if number < 2 : return 0
Line 3,460 ⟶ 3,923:
echo " Perfect = " , perfect
echo " Abundant = " , abundant
</syntaxhighlight>
{{out}}
Line 3,473 ⟶ 3,936:
=={{header|Oforth}}==
<
Integer method: properDivs -- []
Line 3,490 ⟶ 3,953:
"Perfects :" . perfect .cr
"Abundant :" . .cr
; </
{{out}}
Line 3,501 ⟶ 3,964:
=={{header|PARI/GP}}==
<
{
my(v=[0,0,0],t);
Line 3,510 ⟶ 3,973:
v;
}
classify(20000)</
{{out}}
<pre>%1 = [15043, 4, 4953]</pre>
=={{header|Pascal}}==
==={{header|Free Pascal}}===
{{libheader|PrimTrial}}
search for "UNIT for prime decomposition".
<syntaxhighlight lang="pascal">program KindOfN; //[deficient,perfect,abundant]
{$IFDEF FPC}
{$ENDIF}
{$IFDEF WINDOWS} {$APPTYPE CONSOLE}{$ENDIF}
uses
sysutils
{$IFDEF WINDOWS},Windows{$ENDIF}
//alternative copy and paste PrimeDecomp.inc for TIO.RUN
{$I PrimeDecomp.inc}
type
tKindIdx = 0..2;//[deficient,perfect,abundant];
tKind = array[tKindIdx] of Uint64;
procedure
var
pPrimeDecomp :tpPrimeFac;
SumOfKind : tKind;
n: NativeUInt;
c: NativeInt;
T0:Int64;
Begin
writeln('Limit: ',LIMIT);
T0 := GetTickCount64;
fillchar(SumOfKind,SizeOf(SumOfKind),#0);
n := 1;
Init_Sieve(n);
repeat
c := pPrimeDecomp^.pfSumOfDivs-2*n;
c := ORD(c>0)-ORD(c<0)+1;//sgn(c)+1
inc(SumOfKind[c]);
until n
writeln('deficient: ',SumOfKind[0]);
writeln('abundant: ',SumOfKind[2]);
writeln('perfect: ',SumOfKind[1]);
writeln('runtime ',T0/1000:0:3,' s');
writeln;
end;
Begin
InitSmallPrimes; //using PrimeDecomp.inc
GetKind(20000);
GetKind(10*1000*1000);
GetKind(524*1000*1000);
end.</syntaxhighlight>{{out|@TIO.RUN}}
<pre>Limit: 20000
deficient: 15043
abundant: 4953
perfect: 4
runtime 0.003 s
Limit: 1000000
deficient: 752451
abundant: 247545
perfect: 4
runtime 0.052 s
Limit: 524000000
deficient: 394250308
abundant: 129749687
perfect: 5
runtime 32.987 s
Real time: 33.203 s User time: 32.881 s Sys. time: 0.048 s CPU share: 99.17 %
</pre>
Line 3,761 ⟶ 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.
<
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}";</
{{out}}
<pre> 1 Deficient
Line 3,785 ⟶ 4,081:
===Not using a module===
Everything as above, but done more slowly with <code>div_sum</code> providing sum of proper divisors.
<
my($n) = @_;
my $sum = 0;
Line 3,796 ⟶ 4,092:
my %h;
$h{div_sum($_) <=> $_}++ for 1..20000;
say "Perfect: $h{0} Deficient: $h{-1} Abundant: $h{1}";</
=={{header|Phix}}==
<!--<
<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,812 ⟶ 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>
<!--</
{{out}}
<pre>
Line 3,819 ⟶ 4,115:
=={{header|Picat}}==
<
Classes = new_map([deficient=0,perfect=0,abundant=0]),
foreach(N in 1..20_000)
Line 3,866 ⟶ 4,162:
sum_divisors(I,N,Sum0,Sum) =>
sum_divisors(I+1,N,Sum0,Sum).
</syntaxhighlight>
{{out}}
Line 3,872 ⟶ 4,168:
=={{header|PicoLisp}}==
<
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
Line 3,913 ⟶ 4,209:
((> @@ I) (inc 'A)) ) )
(println D P A) ) )
(bye)</
{{Output}}
<pre>
Line 3,921 ⟶ 4,217:
=={{header|PL/I}}==
<
apd: Proc Options(main);
p9a=time();
Line 3,976 ⟶ 4,272:
End;
End;</
{{out}}
<pre>In the range 1 - 20000
Line 3,986 ⟶ 4,282:
=={{header|PL/M}}==
<
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 4,028 ⟶ 4,324:
CALL PRINT(.(' ABUNDANT',13,10,'$'));
CALL EXIT;
EOF</
{{out}}
<pre>15043 DEFICIENT
Line 4,036 ⟶ 4,332:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
function Get-ProperDivisorSum ( [int]$N )
{
Line 4,070 ⟶ 4,366:
"Perfect : $Perfect"
"Abundant : $Abundant"
</syntaxhighlight>
{{out}}
<pre>
Line 4,080 ⟶ 4,376:
===As a single function===
Using the <code>Get-ProperDivisorSum</code> as a helper function in an advanced function:
<syntaxhighlight lang="powershell">
function Get-NumberClassification
{
Line 4,137 ⟶ 4,433:
}
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
1..20000 | Get-NumberClassification
</syntaxhighlight>
{{Out}}
<pre>
Line 4,151 ⟶ 4,447:
=={{header|Processing}}==
<
int deficient = 0, perfect = 0, abundant = 0;
for (int i = 1; i <= 20000; i++) {
Line 4,176 ⟶ 4,472:
}
return sum;
}</
{{out}}
<pre>Deficient numbers less than 20000: 15043
Line 4,183 ⟶ 4,479:
=={{header|Prolog}}==
<
proper_divisors(1, []) :- !.
proper_divisors(N, [1|L]) :-
Line 4,226 ⟶ 4,522:
[LD, LA, LP]),
format("took ~f seconds~n", [Dur]).
</syntaxhighlight>
{{out}}
<pre>
Line 4,237 ⟶ 4,533:
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
EnableExplicit
Line 4,274 ⟶ 4,570:
CloseConsole()
EndIf
</syntaxhighlight>
{{out}}
Line 4,288 ⟶ 4,584:
===Python: Counter===
Importing [[Proper_divisors#Python:_From_prime_factors|Proper divisors from prime factors]]:
<
>>> from collections import Counter
>>>
Line 4,302 ⟶ 4,598:
>>> classes.most_common()
[('deficient', 15043), ('abundant', 4953), ('perfect', 4)]
>>> </
{{out}}
Line 4,315 ⟶ 4,611:
{{Works with|Python|3.7}}
In terms of a single fold:
<
from itertools import accumulate, chain, groupby, product
Line 4,423 ⟶ 4,719:
# MAIN ---
if __name__ == '__main__':
main()</
and the main function could be rewritten in terms of an nthArrow abstraction:
<
def nthArrow(f):
'''A simple function lifted to one which applies to a
Line 4,437 ⟶ 4,733:
x if m != i else f(x) for i, x in enumerate(v)
]
return lambda tpl: lambda n: tuple(go(tpl, n))</
as something like:
<
def deficientPerfectAbundantCountsUpTo(n):
'''Counts of deficient, perfect, and abundant
Line 4,453 ⟶ 4,749:
)
)
return reduce(go, range(1, 1 + n), (0, 0, 0))</
{{Out}}
Line 4,462 ⟶ 4,758:
=== The Simple Way ===
<
an = 0
dn = 0
Line 4,481 ⟶ 4,777:
print(str(pn) + " Perfect Numbers")
print(str(an) + " Abundant Numbers")
print(str(dn) + " Deficient Numbers")</
{{Out}}
Line 4,495 ⟶ 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'').
<
st = time()
pn, an, dn = 0, 0, 0
Line 4,533 ⟶ 4,829:
print(str(dn) + " Deficient Numbers")
print(et2 * 1000, "ms\n")
print (et1 / et2,"times faster")</
{{out|Output @ Tio.run using Python 3 (PyPy)}}
<pre>4 Perfect Numbers
Line 4,552 ⟶ 4,848:
<code>dpa</code> returns 0 if n is deficient, 1 if n is perfect and 2 if n is abundant.
<
[ factors -1 pluck
Line 4,569 ⟶ 4,865:
say "Deficient = " echo cr
say " Perfect = " echo cr
say " Abundant = " echo cr</
{{out}}
Line 4,581 ⟶ 4,877:
{{Works with|R|3.3.2 and above}}
<syntaxhighlight lang="r">
# Abundant, deficient and perfect number classifications. 12/10/16 aev
require(numbers);
Line 4,596 ⟶ 4,892:
}
propdivcls(20000);
</
{{Output}}
Line 4,613 ⟶ 4,909:
=={{header|Racket}}==
<
(require math)
(define (proper-divisors n) (drop-right (divisors n) 1))
Line 4,626 ⟶ 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)))</
{{out}}
Line 4,639 ⟶ 4,935:
(formerly Perl 6)
{{Works with|rakudo|2018.12}}
<syntaxhighlight lang="raku"
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
Line 4,647 ⟶ 4,943:
}
say bag (1..20000).map: { propdivsum($_) <=> $_ }</
{{out}}
<pre>Bag(Less(15043), More(4953), Same(4))</pre>
Line 4,653 ⟶ 4,949:
=={{header|REXX}}==
===version 1===
<
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,675 ⟶ 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. */</
{{out|output|text= when using the default input:}}
<pre>
Line 4,691 ⟶ 4,987:
" 100k " " " '''20%''' "
" 1m " " " '''30%''' "
<
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,715 ⟶ 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. */</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}}
Line 4,722 ⟶ 5,018:
===version 2===
<
Call time 'R'
cnt.=0
Line 4,772 ⟶ 5,068:
sum=sum+word(list,i)
End
Return sum</
{{out}}
<pre>In the range 1 - 20000
Line 4,781 ⟶ 5,077:
=={{header|Ring}}==
The following classifies the first few numbers of each type.
<syntaxhighlight lang="ring">
n = 30
perfect(n)
Line 4,796 ⟶ 5,093:
else see " is a abundant number" + nl ok
next
</syntaxhighlight>
===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:
<
puts "Deficient: #{res[-1]} Perfect: #{res[0]} Abundant: #{res[1]}"
</syntaxhighlight>
{{out}}<pre>
Deficient: 15043 Perfect: 4 Abundant: 4953
Line 4,811 ⟶ 5,198:
With [[proper_divisors#Rust]] in place:
<
// deficient starts at 1 because 1 is deficient but proper_divisors returns
// and empty Vec
Line 4,830 ⟶ 5,217:
deficient, perfect, abundant);
}
</syntaxhighlight>
{{out}}
Line 4,840 ⟶ 5,227:
=={{header|Scala}}==
<
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(",") + ")")</
{{out}}
<pre>Deficient: 15043
Line 4,852 ⟶ 5,239:
=={{header|Scheme}}==
<
(define (classify n)
(define (sum_of_factors x)
Line 4,877 ⟶ 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>
=={{header|Seed7}}==
<
const func integer: sumProperDivisors (in integer: number) is func
Line 4,918 ⟶ 5,305:
writeln("Perfect: " <& perfect);
writeln("Abundant: " <& abundant);
end func;</
{{out}}
Line 4,926 ⟶ 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}}==
<
var h = Hash()
{|i| ++(h{propdivsum(i) <=> i} := 0) } << 1..20000
say "Perfect: #{h{0}} Deficient: #{h{-1}} Abundant: #{h{1}}"</
{{out}}
<pre>
Line 4,940 ⟶ 5,350:
=={{header|Swift}}==
{{trans|C}}
<
var perfects = 0 // sumPd = n
var abundants = 0 // sumPd > n
Line 4,980 ⟶ 5,390:
}
println("There are \(deficients) deficient, \(perfects) perfect and \(abundants) abundant integers from 1 to 20000.")</
{{out}}<pre>There are 15043 deficient, 4 perfect and 4953 abundant integers from 1 to 20000.</pre>
=={{header|Tcl}}==
<
if {$n == 1} {return 0}
set divs 1
Line 5,028 ⟶ 5,438:
foreach {kind count} [lsort -stride 2 -index 1 -integer $classes] {
puts "$kind: $count"
}</
{{out}}
Line 5,070 ⟶ 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 5,120 ⟶ 5,530:
If (b@ > 1) c@ = c@ * (b@+1)
Return (c@)</
{{out}}
<pre>Perfect: 4 Deficient: 15043 Abundant: 4953
Line 5,128 ⟶ 5,538:
=={{header|Vala}}==
{{trans|C}}
<
DEFICIENT,
PERFECT,
Line 5,162 ⟶ 5,572:
print(@" $(count_list[Classification.PERFECT]) perfect,");
print(@" $(count_list[Classification.ABUNDANT]) abundant numbers between 1 and 20000.\n");
}</
{{out}}
<pre>
Line 5,169 ⟶ 5,579:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 5,201 ⟶ 5,611:
If n Mod j = 0 Then SumPropers = j + SumPropers
Next
End Function</
{{out}}
<pre>Execution Time : 2,6875 seconds.
Line 5,210 ⟶ 5,620:
=={{header|VBScript}}==
<
Perfect = 0
Abundant = 0
Line 5,232 ⟶ 5,642:
WScript.Echo "Deficient = " & Deficient & vbCrLf &_
"Perfect = " & Perfect & vbCrLf &_
"Abundant = " & Abundant</
{{out}}
<pre>Deficient = 15043
Line 5,240 ⟶ 5,650:
=={{header|Visual Basic .NET}}==
{{trans|FreeBASIC}}
<
Function SumProperDivisors(number As Integer) As Integer
Line 5,272 ⟶ 5,682:
End Sub
End Module</
{{out}}
<pre>The classification of the numbers from 1 to 20,000 is as follows :
Line 5,280 ⟶ 5,690:
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++ {
Line 5,309 ⟶ 5,719:
println("There are $a abundant numbers between 1 and 20000")
println("There are $p perfect numbers between 1 and 20000")
}</
{{out}}
Line 5,317 ⟶ 5,727:
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}}
<
var d = 0
Line 5,337 ⟶ 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")</
{{out}}
Line 5,344 ⟶ 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}}==
<
[CntD:= 0; CntP:= 0; CntA:= 0;
for Num:= 1 to 20000 do
Line 5,362 ⟶ 5,854:
Text(0, "Perfect: "); IntOut(0, CntP); CrLf(0);
Text(0, "Abundant: "); IntOut(0, CntA); CrLf(0);
]</
{{out}}
Line 5,373 ⟶ 5,865:
=={{header|Yabasic}}==
{{trans|AWK}}
<
Deficient = 0
Line 5,407 ⟶ 5,899:
end if
return sum
end sub</
=={{header|zkl}}==
{{trans|D}}
<
fcn classify(n){
Line 5,423 ⟶ 5,915:
abundant :=classified.filter('==(1)).len();
println("Deficient=%d, perfect=%d, abundant=%d".fmt(
classified.len()-perfect-abundant, perfect, abundant));</
{{out}}<pre>Deficient=15043, perfect=4, abundant=4953</pre>
=={{header|ZX Spectrum Basic}}==
Solution 1:
<
20 FOR i=2 TO 20000
30 LET sum=1
Line 5,442 ⟶ 5,934:
130 PRINT "Number deficient: ";nd
140 PRINT "Number perfect: ";np
150 PRINT "Number abundant: ";na</
Solution 2 (more efficient):
<
20 FOR j=1 TO 20000
30 GO SUB 120
Line 5,463 ⟶ 5,955:
170 NEXT i
180 LET sump=sum
190 RETURN</
|