representations.sf 799 B

12345678910111213141516171819202122232425262728293031323334
  1. #!/usr/bin/ruby
  2. # A perfect square N has a splitting representation (S) if it's possible to segment
  3. # the decimal representation of N into a list of integers L, such that sum(L) = sqrt(n).
  4. # See also:
  5. # https://oeis.org/A104113
  6. # https://projecteuler.net/problem=719
  7. func S_representation(n) {
  8. var v = n.isqrt
  9. var D = n.digits
  10. for k in (1 .. D.len>>1) {
  11. combinations(D.len, k, {|*indices|
  12. var t = D.segment(indices...)
  13. if (t.sum{.digits2num} == v) {
  14. return t
  15. }
  16. })
  17. }
  18. return []
  19. }
  20. File(ARGV[0] \\ "data.txt").open_r.each{|line|
  21. var n = line.nums.tail
  22. n > 1 || next
  23. var arr = S_representation(n)
  24. assert(arr.len > 0)
  25. say ("sqrt(#{n}) = ", arr.flip.map{.digits2num}.grep.join(' + '))
  26. }