061 Cyclical figurate numbers.pl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # Date: 16 August 2016
  4. # License: GPLv3
  5. # Website: https://github.com/trizen
  6. # https://projecteuler.net/problem=61
  7. # Runtime: 0.087s
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. use ntheory qw(forperm is_square sqrtint vecsum);
  12. sub is_polygonal {
  13. my ($n, $k) = @_;
  14. my $s = 8 * ($k - 2) * $n + ($k - 4) * ($k - 4);
  15. is_square($s)
  16. && ((sqrtint($s) + $k - 4) % (2 * ($k - 2)) == 0);
  17. }
  18. my (%trig, %square, %penta, %hexa, %hepta, %octa);
  19. foreach my $n (1000 .. 9999) {
  20. my ($h, $t) = (substr($n, 0, 2), substr($n, -2));
  21. is_polygonal($n, 3) && undef $trig{$h}{$t};
  22. is_polygonal($n, 4) && undef $square{$h}{$t};
  23. is_polygonal($n, 5) && undef $penta{$h}{$t};
  24. is_polygonal($n, 6) && undef $hexa{$h}{$t};
  25. is_polygonal($n, 7) && undef $hepta{$h}{$t};
  26. is_polygonal($n, 8) && undef $octa{$h}{$t};
  27. }
  28. my (@a) = (\%trig, \%square, \%penta, \%hexa, \%hepta, \%octa);
  29. forperm {
  30. my @h = @a[@_];
  31. foreach my $ah (keys %{$h[0]}) {
  32. foreach my $at (keys %{$h[0]{$ah}}) {
  33. foreach my $bt (keys %{$h[1]{$at}}) {
  34. foreach my $ct (keys %{$h[2]{$bt}}) {
  35. foreach my $dt (keys %{$h[3]{$ct}}) {
  36. foreach my $et (keys %{$h[4]{$dt}}) {
  37. if (exists $h[5]{$et}{$ah}) {
  38. my @nums = split(' ', "$ah$at $at$bt $bt$ct $ct$dt $dt$et $et$ah");
  39. say "sum(@nums) = ", vecsum(@nums);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }
  47. } scalar(@a);