[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Prime Numbers



On Mon, 16 Aug 1999 17:48:06 GMT, Bart Lateur wrote:


>So a different algorithm should be able to give a large speed boost.

Here's my code. Let the benchmarks begin! ;-)

BTW this code takes only a few SECONDS to calculate the first 1000
primes.

    #! perl -w

    $, = "\n"; $\ = "\n\n";
    print primes(1000);

    sub primes {
        my $count = shift;
        my @primes = (2); # I know that...
        for(my $candidate = 3; @primes<$count; $candidate+= 2) {
            my $itsaprime = 1;
            foreach my $prime (@primes) {
                last if  $prime*$prime>$candidate;
                unless($candidate % $prime) {
                    $itsaprime = 0;
                    last;
                }
            }
            push @primes, $candidate if $itsaprime;
        }
        return wantarray?@primes:\@primes;
    }
__END__

	Bart.

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org