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