right_triangle_primes.pl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 11 April 2015
  5. # https://github.com/trizen
  6. # A number triangle, with the primes highlighted in blue
  7. # (there are some lines that have more primes than others)
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. use GD::Simple;
  12. use ntheory qw(is_prime);
  13. my $n = 1000000; # duration: about 5 seconds
  14. sub limit {
  15. my ($n) = @_;
  16. (sqrt(8 * $n + 1) - 1) / 2;
  17. }
  18. sub round {
  19. my ($n) = @_;
  20. ($n**2 + $n) / 2;
  21. }
  22. my $lim = int(limit($n));
  23. my $num = round($lim);
  24. # create a new image
  25. my $img = GD::Simple->new($lim, $lim);
  26. my $counter = 1;
  27. my $white = 1;
  28. $img->fgcolor('white');
  29. foreach my $i (0 .. $lim - 1) {
  30. $img->moveTo(0, $i);
  31. foreach my $j (0 .. $i) {
  32. ##print $counter, ' ';
  33. if (is_prime($counter)) {
  34. if ($white) {
  35. $img->fgcolor('blue');
  36. $white = 0;
  37. }
  38. }
  39. elsif (not $white) {
  40. $img->fgcolor('white');
  41. $white = 1;
  42. }
  43. $img->line(1);
  44. ++$counter;
  45. }
  46. ##print "\n";
  47. }
  48. open my $fh, '>:raw', 'right_triangle_primes.png';
  49. print $fh $img->png;
  50. close $fh;