Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Calculate primes!

by azerton (Beadle)
on May 05, 2004 at 14:28 UTC ( [id://350789]=sourcecode: print w/replies, xml ) Need Help??
Category: Fun
Author/Contact Info Azerton 2004
Description: This program will calculate primes for you.
#!/usr/bin/perl


##################################
### To find the largest prime! ###
###     by Azerton 2004        ###
##################################

system(clear);

#ASK FOR INPUT
print "Created by Azerton, 2004\n";
print "I will calculate the primes from 1 to the number you enter. Wha
+t is the maximum number to check?\n";
START:
$max=<STDIN>;  #max value to calculate
if ($max<=1){
die "Negatives or 0 not allowed!\n";
}


$getal=$max+1; #I use this now
$teller=0; # A/B would give A in this case
$deeltal=2; # A/B would give B in this case



for ($max;$getal-=1;$getal>=0)
{

#$getal -=1; Check if it's a prime, by going down 1 value
$deeltal=2;
$teller=0;
        while($getal % $deeltal!=0 && $deeltal+2<=$getal){
            $teller+=1;
            $deeltal+=1;

        } #important while: closed

        if($teller+3==$getal){
        push(@priemlijst,$getal);
        } else
        {
        #Don't you dare to do anything
        } #We don't have a prime, too bad

} # Close main for
system (clear);
push(@priemlijst,2); #Don't forget number 2!
@priemlijst=reverse(@priemlijst); #Tidy the room
print "The primes from  1 to $max are : @priemlijst \n";
Replies are listed 'Best First'.
Re: Calculate primes!
by Juerd (Abbot) on May 05, 2004 at 22:38 UTC

    This has done a zillion times before, so I guess you posted it for critique.

    Some comments, in random order:

    • use strict.
      • Declare variables.
      • Quote strings.
    • use warnings.
    • Don't use Dutch variable names.
    • Use steps of 2, not one.
    • Every prime number (except for 2 and 3) is 6x - 1 or 6x + 1.
    • The inner loops needs only to check up to the square root.
    • As calculating primes gets much slower as the numbers are larger, consider printing them immedately instead of storing them first.
    • Indent.
    • Don't have empty else blocks.
    • Don't comment closing brackets. If what they close is unclear, something of your style is wrong and needs to be fixed.
    • Think about your style anyway. I find it hard to read. Whitespace and lining up can do wonders.

    To prove the last point, here's your code, with only stylistic changes made and the addition of strict compliancy. (Note: untested code!)

    #!/usr/bin/perl -w use strict; system 'clear'; print "I will calculate the primes from 1 to the number you enter. Wha +t is the maximum number to check?\n"; my $max = <STDIN>; $max > 0 or die "Negatives or 0 not allowed!\n"; my $getal = $max + 1; for (; $getal--; $getal >= 0) { my $deeltal = 2; # A/B would give B in this case my $teller = 0; # A/B would give A in this case while ($getal % $deeltal != 0 and $deeltal + 2 <= $getal) { $teller++; $deeltal++; } if ($teller + 3 == $getal) { push @priemlijst, $getal; } } system 'clear'; push @priemlijst, 2; # Don't forget number 2! @priemlijst = reverse @priemlijst; print "The primes from 1 to $max are: @priemlijst\n";
    Counting backwards means you have to reverse later. Why make it so hard for yourself? Here is how I would probably code a brute force prime number generator:
    #!/usr/bin/perl -w use strict; $| = 1; chomp(my $max = <STDIN>); print "\n2 "; N: for my $i (3 .. $max - 1) { for my $k (2 .. $i - 1) { next N if $i % $k == 0; } print $i, " "; } print "\n";
    Or, with the two optimizations implemented:
    #!/usr/bin/perl -w use strict; $| = 1; chomp(my $max = <STDIN>); print "\n2 "; N: for (my $i = 3; $i < $max; $i += 2) { next unless $i % 6 == 5 or $i % 6 == 1; for (my $k = 3; $k < sqrt $i; $k += 2) { next N if $i % $k == 0; } print $i, " "; } print "\n";
    The best way to learn from this is to study the differences between these four versions and the many other prime number generators.

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

      Thanks for your reply, I appreciate it. I just coded it to practice my perl skills, it was not so much about the 'content' itself. The Dutch variable names: I wanted to show the code to my teacher so I commented in Dutch. I translated it to English to put it online, but I forgot to transform the variable names, so sorry for that. I was indeed a bit lazy when I was coding cause I never really thought about using tabs and whitelines cause I knew it would be a very small piece of code, but I know it's not an excuse hehe :) Anyway thanks for the hints, hope to hear from you later cheers azerton
Re: Calculate primes!
by Ovid (Cardinal) on May 05, 2004 at 16:19 UTC

    See Prime Iterator for some interesting code on finding primes. Let me know if you don't understand how the code works.

    Cheers,
    Ovid

    New address of my CGI Course.

Re: Calculate primes!
by Plankton (Vicar) on May 05, 2004 at 15:56 UTC
    Cool script ... I think you'd be interested in this

    Plankton: 1% Evil, 99% Hot Gas.
      thanks for the link and the compliment. Just felt like sharing it with you guys.
Re: Calculate primes!
by PERLscienceman (Curate) on May 06, 2004 at 02:03 UTC
    Cool Script Indeed.... you may also want to have a look at Bundle::PPT, "Perl Power Tools", also simply known as ppt if you are going to install from the ActiveState PPM on Win32. It contains a utility called primes. I installed the ppt package on Windows XP with ActivePerl 5.8.1 Build 807 and decided to give it a whirl.
    Command line usage: primes start stop
    I tried it out and got the following results:
    C:\>primes 4 50 5 7 11 13 17 19 23 29 31 37 41 43 47
    UPDATE:
    After exploring CPAN some more I found two additional modules which overtly caught my eye:
    Math::Prime::Simple
    Math::Big (contains a subroutine for calculating primes)
Re: Calculate primes!
by QM (Parson) on May 05, 2004 at 21:25 UTC
    I'll point you to the one that started me thinking:
    Abigail-II's C.L.P.M. Post

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-25 15:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found