in reply to Re: a close prime number
in thread a close prime number
The speed of the is_prime function can be increase by about 140% by using the 2 4 trick used below.
This version skips all of the numbers that are divisable by 2 and 3. Not checking numbers divisable by 2 is obvious, but not checking numbers divisable by 3 is less so, but reduces the search space by 25%.sub is_prime { my %prime = map { $_ => 1 } (2, 3, 5, 7); my %not_prime; return sub { my $n = shift; return 1 if $prime{ $n }; return 0 if $n % 2 == 0 || $n % 3 == 0 || exists $not_prime{ $n }; my $last = int sqrt $n; for ( my $x = 5; $x <= $last ;) { return $not_prime{ $n } = 0 if $n % $x == 0; $x += 2; return $not_prime{ $n } = 0 if $n % $x == 0; $x += 4; } return $prime{ $n } = 1; }; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: a close prime number
by Limbic~Region (Chancellor) on Feb 15, 2005 at 22:32 UTC | |
Re^3: a close prime number
by RazorbladeBidet (Friar) on Feb 14, 2005 at 19:01 UTC | |
by dragonchild (Archbishop) on Feb 14, 2005 at 19:11 UTC | |
by RazorbladeBidet (Friar) on Feb 14, 2005 at 19:15 UTC |
In Section
Seekers of Perl Wisdom