triangle_primes_irregular.pl 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. ## Vertical lines are represented by:
  8. # n^2 - 2n + 2
  9. # n^2 - n + 1
  10. # n^2
  11. # n^2 + n - 1
  12. # n^2 + 2n - 2
  13. # ...
  14. ## Horizontal lines are represented by:
  15. # 1
  16. # n + 1
  17. # 2n + 3
  18. # 3n + 7
  19. # 4n + 13
  20. # 5n + 21
  21. # 6n + 31
  22. # 7n + 43
  23. # ...
  24. use 5.010;
  25. use strict;
  26. use warnings;
  27. use GD::Simple;
  28. use ntheory qw(is_prime);
  29. my $rows = shift(@ARGV) // 2000; # duration: about 12 seconds
  30. my $white = 1;
  31. # create a new image
  32. my $img = GD::Simple->new($rows, $rows);
  33. $img->fgcolor('white');
  34. foreach my $i (0 .. $rows - 1) {
  35. $img->moveTo(0, $i);
  36. foreach my $j ($i .. $rows - 1) {
  37. my $num = $i * $j + 1;
  38. #printf "%3d%s", $num, ' ';
  39. if (is_prime($num)) {
  40. if ($white) {
  41. $img->fgcolor('blue');
  42. $white = 0;
  43. }
  44. }
  45. elsif (not $white) {
  46. $img->fgcolor('white');
  47. $white = 1;
  48. }
  49. $img->line(1);
  50. }
  51. #print "\n";
  52. }
  53. open my $fh, '>:raw', 'triangle_primes_irregular.png';
  54. print $fh $img->png;
  55. close $fh;
  56. __END__
  57. 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
  58. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
  59. 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
  60. 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58
  61. 17 21 25 29 33 37 41 45 49 53 57 61 65 69 73 77
  62. 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96
  63. 37 43 49 55 61 67 73 79 85 91 97 103 109 115
  64. 50 57 64 71 78 85 92 99 106 113 120 127 134
  65. 65 73 81 89 97 105 113 121 129 137 145 153
  66. 82 91 100 109 118 127 136 145 154 163 172
  67. 101 111 121 131 141 151 161 171 181 191
  68. 122 133 144 155 166 177 188 199 210
  69. 145 157 169 181 193 205 217 229
  70. 170 183 196 209 222 235 248
  71. 197 211 225 239 253 267
  72. 226 241 256 271 286
  73. 257 273 289 305
  74. 290 307 324
  75. 325 343
  76. 362