triangle_primes.pl 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 10 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. # Inspired by: https://www.youtube.com/watch?v=iFuR97YcSLM
  9. use 5.010;
  10. use strict;
  11. use warnings;
  12. use GD::Simple;
  13. use ntheory qw(is_prime);
  14. my $i = 1;
  15. my $j = 1;
  16. my $n = shift(@ARGV) // 8000000; # duration: about 45 seconds
  17. my $limit = int(sqrt($n)) - 1;
  18. my %top; # count the number of primes on vertical lines
  19. my $top = 10; # how many lines to display at the end
  20. # create a new image
  21. my $img = GD::Simple->new($limit * 2, $limit + 1);
  22. my $white = 0;
  23. for my $m (reverse(0 .. $limit)) {
  24. ##print " " x $m;
  25. my $pos = $m;
  26. $img->moveTo($m, $i - 1);
  27. for my $n ($j .. $i**2) {
  28. ##print $j;
  29. if (is_prime($j)) {
  30. $white = 0;
  31. $img->fgcolor('blue');
  32. $top{$pos}{count}++;
  33. $top{$pos}{first} //= $j;
  34. }
  35. elsif (not $white) {
  36. $white = 1;
  37. $img->fgcolor('white');
  38. }
  39. $img->line(1);
  40. ++$pos;
  41. ++$j;
  42. }
  43. ++$i;
  44. ##print "\n";
  45. }
  46. say "=> Top vertical lines: ";
  47. foreach my $i (sort { $top{$b}{count} <=> $top{$a}{count} } keys %top) {
  48. state $counter = 0;
  49. say "$i:\t$top{$i}{count} (first prime: $top{$i}{first})";
  50. last if ++$counter == $top;
  51. }
  52. open my $fh, '>:raw', 'triangle_primes.png';
  53. print $fh $img->png;
  54. close $fh;