Perfect numbers: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: changed whitespace for some REXX comments.)
(→‎Modules: The ntheory module has sped up a lot; reflect new speeds and show new is_mersenne_prime.)
Line 1,294: Line 1,294:
<lang perl>use ntheory qw/divisor_sum/;
<lang perl>use ntheory qw/divisor_sum/;
sub is_perfect { my $n = shift; divisor_sum($n) == 2*$n; }</lang>
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):
Use this naive method to show the first 5. Takes about 15 seconds:
<lang perl>use ntheory qw/divisor_sum/;
<lang perl>use ntheory qw/divisor_sum/;
for (1..33550336) {
for (1..33550336) {
print "$_\n" if divisor_sum($_) == 2*$_;
print "$_\n" if divisor_sum($_) == 2*$_;
}</lang>
}</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.
Or we can be clever and look for 2^(p-1) * (2^p-1) where 2^p -1 is prime. The first 20 takes about a second.
<lang perl>use ntheory qw/forprimes is_prime/;
<lang perl>use ntheory qw/forprimes is_prime/;
use bigint;
use bigint;
Line 1,320: Line 1,320:
... 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423 ...
... 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423 ...
</pre>
</pre>

We can speed this up even more using a faster program for printing the large results, as well as a faster primality solution. The first 38 in about 1 second with most of the time printing the large results. Caveat: this goes well past the current bound for odd perfect numbers and does not check for them.
<lang perl>use ntheory qw/forprimes is_mersenne_prime/;
use Math::GMP qw/:constant/;
forprimes {
print "$_\t", (2**$_-1)*2**($_-1),"\n" if is_mersenne_prime($_);
} 7_000_000;</lang>


=={{header|Perl 6}}==
=={{header|Perl 6}}==