in reply to Calculate primes!

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

Some comments, in random order:

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' }

Replies are listed 'Best First'.
Re: Re: Calculate primes!
by azerton (Beadle) on May 06, 2004 at 21:36 UTC
    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