719 Number Splitting.pl 901 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 01 July 2020
  4. # https://github.com/trizen
  5. # Number Splitting
  6. # https://projecteuler.net/problem=719
  7. # Runtime: 8 min, 14 sec
  8. use 5.020;
  9. use warnings;
  10. use ntheory qw(:all);
  11. use experimental qw(signatures);
  12. sub isok ($i, $j, $d, $e, $n, $sum = 0) {
  13. if ($sum + join('', @{$d}[$i .. $e]) < $n) {
  14. return 0;
  15. }
  16. my $new_sum = $sum + join('', @{$d}[$i .. $j]);
  17. if ($new_sum > $n) {
  18. return 0;
  19. }
  20. if ($new_sum == $n and $j >= $e) {
  21. return 1;
  22. }
  23. if ($j + 1 <= $e) {
  24. isok($j + 1, $j + 1, $d, $e, $n, $new_sum) && return 1;
  25. isok($i, $j + 1, $d, $e, $n, $sum) && return 1;
  26. }
  27. return 0;
  28. }
  29. my $sum = 0;
  30. foreach my $n (2 .. 1e6) {
  31. my @d = todigits($n * $n);
  32. if (isok(0, 0, \@d, $#d, $n)) {
  33. say $n * $n;
  34. $sum += $n * $n;
  35. }
  36. }
  37. say "Total: $sum";