Syntactic Confectionery Delight PerlMonks

Re: a close prime number

by renz (Scribe)
 on Feb 11, 2005 at 22:45 UTC ( #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.

Create A New User
Node Status?
node history
Node Type: note [id://430337]
help
Chatterbox?
 [choroba]: I'm curious which part of your signature do they find offensive. [LanX]: they? [LanX]: click! [choroba]: they

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (12)
As of 2017-05-24 20:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favorite model of computation is ...

Results (186 votes). Check out past polls.