Abundant, deficient and perfect number classifications: Difference between revisions

Add Perl
(J)
(Add Perl)
Line 46:
 
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).
 
=={{header|Perl}}==
===Using a module===
{{libheader|ntheory}}
We can use the <tt>&lt;=&gt;</tt> operator to return a comparison of -1, 0, or 1, which classifies the results. Let's look at the values from 1 to 30:
<lang perl>use ntheory qw/divisor_sum/;
say join " ", map { divisor_sum($_)-$_ <=> $_ } 1..30;</lang>
{{out}}
<pre>-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</pre>
We can see 6 is the first [[wp:Perfect_number|perfect number]], 12 is the first [[wp:Abundant_number|abundant number]], and 1 is classified as a [[wp:Deficient_number|deficient number]].
 
Showing the totals for the first 20k numbers:
<lang perl>use ntheory qw/divisor_sum/;
my %h;
$h{divisor_sum($_)-$_ <=> $_}++ for 1..20000;
say "Perfect: $h{0} Deficient: $h{-1} Abundant: $h{1}";</lang>
{{out}}
<pre>Perfect: 4 Deficient: 15043 Abundant: 4953</pre>
 
=={{header|Python}}==
Anonymous user