Jump to content

Perfect numbers: Difference between revisions

(updated FunL)
(→‎{{header|Perl}}: Add module)
Line 1,153:
 
=={{header|Perl}}==
== Functions ==
<lang perl>sub perf {
my $n = shift;
Line 1,170 ⟶ 1,171:
$n == sum(0, grep {$n % $_ == 0} 1..$n-1);
}</lang>
== Modules ==
The functions above are terribly slow. As usual, this is easier and faster with modules. Both ntheory and Math::Pari have useful functions for this.
{{libheader|ntheory}}
A simple predicate:
<lang perl>use ntheory qw/divisor_sum/;
sub is_perfect { my $n = shift; divisor_sum($n) == 2*$n; }</lang>
Use this naive method to show the first 5. Takes about 30 seconds (half the time Pari/GP takes with this method):
<lang perl>use ntheory qw/divisor_sum/;
for (1..33550336) {
print "$_\n" if divisor_sum($_) == 2*$_;
}</lang>
Or we can be clever and look for 2^(p-1) * (2^p-1) where 2^p -1 is prime. The first 17 are found in ~1 second, with the first 20 taking a bit under 10 seconds.
<lang perl>use ntheory qw/forprimes is_prime/;
use bigint;
forprimes {
my $n = 2**$_ - 1;
print "$_\t", $n * 2**($_-1),"\n" if is_prime($n);
} 2, 4500;</lang>
{{out}}
<pre>
2 6
3 28
5 496
7 8128
13 33550336
17 8589869056
19 137438691328
31 2305843008139952128
61 2658455991569831744654692615953842176
89 191561942608236107294793378084303638130997321548169216
... 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423 ...
</pre>
 
=={{header|Perl 6}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.