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!)
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; 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";
Or, with the two optimizations implemented:#!/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";
The best way to learn from this is to study the differences between these four versions and the many other prime number generators.#!/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";
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 |