Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Rotationally Prime Numbers Revisited

by shemp (Deacon)
on Mar 25, 2005 at 00:53 UTC ( [id://442241]=note: print w/replies, xml ) Need Help??


in reply to Rotationally Prime Numbers Revisited

Well, i just wrote my own prime checker that is really a growing sieve that goes as far as it needs to for the prime to check. It caches a hash of all the primes known so far, so that primeness only needs to be calculated once, and is quite fast. I didnt even bother explicitly eliminating even numbers in advance, but that would be no biggie. The general sieve'ing can be improved some too. So here it is:
{ my %prime_cache; my $max_checked; BEGIN { $prime_cache{2} = undef; $max_checked = 2; } sub is_prime { my ($to_check) = @_; sieve_up_to($to_check); return exists $prime_cache{$to_check}; } sub sieve_up_to { my ($to_check) = @_; while ( $max_checked < $to_check ) { sieve_part($to_check); } } sub sieve_part { my ($to_check) = @_; $to_check++ if !($to_check % 2); my $max_this_part = $to_check; if ( ($max_checked * $max_checked) < $to_check ) { $max_this_part = $max_checked * $max_checked; } my %to_sieve = map { $_ => undef } ($max_checked + 1 .. $max_t +his_part); for my $prime (keys %prime_cache) { my $base = $max_checked - ($max_checked % $prime) + $prime +; while ( $base <= $max_this_part ) { delete $to_sieve{$base}; $base += $prime; } } while ( my $new_prime = each %to_sieve ) { $prime_cache{$new_prime} = undef; } $max_checked = $max_this_part; } }

Replies are listed 'Best First'.
Re^2: Rotationally Prime Numbers Revisited
by Limbic~Region (Chancellor) on Mar 25, 2005 at 01:04 UTC
    shemp,
    As tall_man and I have discussed, is_prime() isn't really a factor. I had considered both the sieve method as well as C. Given that my candidate numbers reach 100 million in about 40 seconds on my mediocre machine, I prefer keeping it simple (and pure Perl).

    Cheers - L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://442241]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-04-24 21:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found