factor_triangle.pl 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 14 September 2016
  5. # Website: https://github.com/trizen
  6. # Generates a triangle with non-prime and non-power numbers,
  7. # each number connected through a line to its prime factors.
  8. # The triangles that are forming, are the prime numbers.
  9. # For example, the first two triangles are 2 and 3 respectively.
  10. use strict;
  11. use warnings;
  12. use Imager;
  13. use ntheory qw(is_prime is_power factor);
  14. use POSIX qw(ceil);
  15. use List::Util qw(uniq);
  16. use Memoize qw(memoize);
  17. memoize('get_point');
  18. my $limit = 10;
  19. my $scale = 1000;
  20. my $red = Imager::Color->new('#ff0000');
  21. my $img = Imager->new(xsize => 2 * $limit * $scale,
  22. ysize => $limit * $scale);
  23. sub get_point {
  24. my ($n) = @_;
  25. my $row = ceil(sqrt($n));
  26. my $cell = 2 * $row - 1 - $row**2 + $n;
  27. ($scale * $cell, $scale * $row);
  28. }
  29. foreach my $n (1 .. $scale) {
  30. if (not is_prime($n) and not is_power($n)) {
  31. my ($x1, $y1) = get_point($n);
  32. my @f = uniq(factor($n));
  33. foreach my $factor (@f) {
  34. my ($x2, $y2) = get_point($factor);
  35. $img->line(
  36. x1 => ($limit * $scale - $y1 - 1) + $x1,
  37. y1 => $y1,
  38. x2 => ($limit * $scale - $y2 - 1) + $x2,
  39. y2 => $y2,
  40. color => $red
  41. );
  42. }
  43. }
  44. }
  45. $img->write(file => 'factor_triangle.png');