#!/usr/local/bin/perl use strict; use warnings; use Tk; my $NumOfPrimes = 0; my ($colr, $counter); my($o, $s) = (250, 20); my($pi, $x, $y) = (3.1415926, 0, 0); print "type the maximum number for the prime spiral \n"; my $lastnumber = <>; print "please wait \n"; my $mw = MainWindow->new; my $c = $mw->Canvas(-width => 500, -height => 500); $c->pack; $c->createLine(50, 250, 450, 250); $c->createText(10, 250, -fill => 'blue', -text => 'X'); $c->createLine(250, 50, 250, 450); $c->createText(250, 10, -fill => 'blue', -text => 'Y'); my $num = 0; my $order = 0; my $pnts = 0; my $pntcycle = 0; OUTER: for (my $i= 1; $i <= 250; $i += 1) { $order=$order+1; if ($order == 5) {$order = 1;} ++$pntcycle; if ($pntcycle == 3) { $pntcycle = 1; ++$pnts; } $counter = 0; while ($counter <= $pnts) { $counter++; ++$num; # This is the more common way to increment a number if ($num == $lastnumber + 1) { last OUTER } my $b = is_prime($num); if ($b != 0) {$colr = "white"; $NumOfPrimes = $NumOfPrimes + 1;} if ($b == 0) {$colr = "black";} if ($order == 1) {$x = $x + 1;} elsif ($order == 2) {$y = $y - 1;} elsif ($order == 3) {$x = $x - 1; } elsif ($order == 4) {$y = $y + 1; } $c->createText( $x+$o, $y+$o, -fill => "$colr", -text => '.'); } } MainLoop; BEGIN { # Cache primes for future use, but using a *hash*, NOT an array! # Start with the value "2", which lets us avoid my %primes = ( 2 => 1 ); sub is_prime { my ($num) = @_; if (exists($primes{$num})) { return $primes{$num}; } # Only need to calculate up to sqrt($num). # This is VERY important, especially with larger numbers. # If N is divisible by some factor $f, less than sqrt($N), # then it's also divisible by some other factor $k = $N/$f # which MUST be larger than sqrt($N), and vice versa. my $sqrt = int(sqrt($num)); # Check for division by 2 (special-case) ($num % 2) or return 0; # We've tried 2 as a factor, so any other factors must be odd # (and prime, for that matter). for (my $j = 3; $j <= $sqrt; $j += 2) { if (0 == $num % $j) { # It's NOT a prime. return 0; } } # Cache the prime number and return '1' return $primes{$num} = 1; } }