749 Near Power Sums.pl 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 23 March 2022
  4. # https://github.com/trizen
  5. # Near Power Sums
  6. # https://projecteuler.net/problem=749
  7. # See also:
  8. # https://oeis.org/A300160
  9. # Runtime: 3 minutes, 50 seconds.
  10. use 5.020;
  11. use warnings;
  12. use ntheory qw(:all);
  13. use experimental qw(signatures);
  14. use Algorithm::Combinatorics qw(combinations_with_repetition);
  15. sub S ($n) {
  16. my $sum = 0;
  17. foreach my $k (1 .. $n) {
  18. #for(my $j = 1; ; ++$j) {
  19. foreach my $j (vecmax(1, $k - 2) .. $k + 2) {
  20. my $min = vecprod(powint(2, $j), $k);
  21. my $max = vecprod(powint(9, $j), $k);
  22. length($min) <= $k or last;
  23. length($max) >= $k or next;
  24. say ":: Trying: j = $j and k = $k";
  25. my @powers = map { [$_, powint($_, $j)] } 0 .. 9;
  26. my $iter = combinations_with_repetition(\@powers, $k);
  27. while (my $arr = $iter->next) {
  28. my $t = vecsum(map { $_->[1] } @$arr);
  29. my $r = fromdigits([sort { $b <=> $a } map { $_->[0] } @$arr]);
  30. if ($t > 0 and fromdigits([sort { $b <=> $a } todigits(subint($t, 1))]) == $r) {
  31. say "[-1] Found: ", $t - 1;
  32. $sum += $t - 1;
  33. }
  34. if (fromdigits([sort { $b <=> $a } todigits(addint($t, 1))]) == $r) {
  35. say "[+1] Found: ", $t + 1;
  36. $sum += $t + 1;
  37. }
  38. }
  39. }
  40. }
  41. return $sum;
  42. }
  43. S(2) == 110 or die "Error for S(2)";
  44. S(6) == 2562701 or die "Error for S(6)";
  45. say("Answer: ", S(16));