Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Rotationally Prime Numbers

by dragonchild (Archbishop)
on Jan 29, 2002 at 03:14 UTC ( [id://142225]=note: print w/replies, xml ) Need Help??


in reply to Rotationally Prime Numbers

Neat algorithm. I'll arrogantly rewrite your code to make it what I consider to be more Perlish. :-)

This takes advantage of a number of things some C/C++ programmers may or may not know/be comfortable with.

#!/usr/local/bin/perl use strict; use warnings; use constant DIGITS => (5); my $list = primelist(10 ** DIGITS); $list = rotatelist($list); print $_, $/ for @$list; #----------------------------------------------------------- sub rotatelist { my ($primes) = @_; my %phash; @phash{@{$primes}} = (1) x @{$primes}; my @list; for my $prime (@{$primes}) { my $rotations = rotations($prime); if ($prime == $rotations->[0]) { my $sum = 0; $sum += $phash{$_} || 0 for @$rotations; push @list, $prime if $sum == @{$rotations}; } } return \@list; } #----------------------------------------------------------- sub rotations { my ($num) = @_; my @digs = split '', $num; my @list; for (1 .. length($num)) { push @digs, shift @digs; push @list, join ('', @digs) + 0; } @list = sort(@list); return \@list; } #----------------------------------------------------------- sub primelist { my ($max) = @_; my @primes = (2); for (my $test = 3; $test < $max; $test += 2) { my $stop = sqrt($test); my $isprime = 1; for my $prime (@primes) { last if $prime >= $stop; if ($test % $prime == 0) { $isprime = 0; last; } } push @primes, $test if $isprime; } return \@primes; }

------
We are the carpenters and bricklayers of the Information Age.

Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-16 23:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found