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

Re: a close prime number

by renz (Scribe)
on Feb 11, 2005 at 22:45 UTC ( [id://430337]=note: print w/replies, xml ) Need Help??


in reply to a close prime number

Update: Removed entire program and restructured post around isPrime() -- full code here.

Update2: For those of you who aren't familiar with the problems of Fermat's Little Theorem check out this.

This isn't *exactly* what you wanted, but since mr_mischief and I were talking about it yesterday, and a primality question popped up today, I thought I'd post it. If nothing else, you can make use of isPrime()... It could be easily adapted to check a range of numbers for primes, a task in this case left to the reader.

# thanks to: mr_mischief for help and efficient isPrime() rewrite. sub isPrime { my $num = $_[0]; my $val = 'prime'; if ($num =~ /^\d+$/ && $num >= 2) { my $mod = 2; my $div = int($num / 2); while ($mod <= $div) { ($num % $mod) == 0 ? ($val = 'composite', last) : $mod++; } } else { $val = 'neither'; } print ' ' . $num . ":\t\t$val\n"; } # rz/021005

A couple of nice things about this isPrime() is that it should not be fooled by pseudoprimes (because we aren't exactly using Fermat's little theorem to test for them) or any data that should not be prime (thanks to /^\d+$/). Without that regex, weird things would happen (well, weird in the context of what we are doing), like returning prime for numbers that are obviously not prime:

(3.5 % 2) = 1
(which evaluates to prime -- best to ignore decimals and negatives since they can't be prime anyway.)

/renz.
"Are you merely the spirit of these/ Bones that shelter me?"
--Dax Riggs, Dressed Up In Smoke.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-03-29 13:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found