search.pl 900 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/perl
  2. # Numbers which when chopped into one, two or more parts, added and squared result in the same number
  3. # https://oeis.org/A104113
  4. # Generate terms of the sequence.
  5. # See also:
  6. # https://projecteuler.net/problem=719
  7. use 5.020;
  8. use warnings;
  9. use ntheory qw(:all);
  10. use experimental qw(signatures);
  11. sub isok ($i, $j, $d, $e, $n, $sum = 0) {
  12. if ($sum + join('', @{$d}[$i .. $e]) < $n) {
  13. return 0;
  14. }
  15. my $new_sum = $sum + join('', @{$d}[$i .. $j]);
  16. if ($new_sum > $n) {
  17. return 0;
  18. }
  19. if ($new_sum == $n and $j >= $e) {
  20. return 1;
  21. }
  22. if ($j + 1 <= $e) {
  23. isok($j + 1, $j + 1, $d, $e, $n, $new_sum) && return 1;
  24. isok($i, $j + 1, $d, $e, $n, $sum) && return 1;
  25. }
  26. return 0;
  27. }
  28. foreach my $n (2 .. 1e7) {
  29. my @d = todigits($n * $n);
  30. if (isok(0, 0, \@d, $#d, $n)) {
  31. say $n * $n;
  32. }
  33. }