Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Prime Number Finder

by elusion (Curate)
on Feb 07, 2002 at 22:32 UTC ( #143983=note: print w/ replies, xml ) Need Help??


in reply to Prime Number Finder

Here's the code I've used for this in the past. I believe it's fairly efficent. If you're going to use it like in the root node in this thread, it's best to check only odd numbers, as suggested by ichimunki.

#!usr/bin/perl -w use strict; sub prime { my $number = shift; my $d = 2; my $sqrt = sqrt $number; while(1) { if ($number%$d == 0) { return 0; } if ($d < $sqrt) { $d++; } else { return 1; } } } my $number = $ARGV[0]; print prime($number);

elusion : http://matt.diephouse.com


Comment on Re: Prime Number Finder
Download Code
Re: Re: Prime Number Finder
by Anonymous Monk on May 04, 2002 at 18:08 UTC
    Isn't the math wrong here? I get false primes with this.
      nope! they all look prime to me!
      i like it, i'm gonna use it to explain programming loops to a mathmatician friend. i took the liberty to re-arrange a touch...
      sub isPrime { my $number = shift; my $sqrt = sqrt $number; my $d = 2; while (1) { return 0 if ( $number % $d == 0 ); return 1 if ( $d > $sqrt ); $d++; } }
      In fact, you're right, because numbers which only can be devided in 1, themselves and their square root will be marked as prime in this way. make the < into a <= and it is solved.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2015-07-03 15:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (53 votes), past polls