Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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.)

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://430337]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (11)
As of 2017-02-24 15:33 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (356 votes). Check out past polls.