number_of_representations_as_sum_of_3_triangles.sf 837 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 02 March 2018
  4. # https://github.com/trizen
  5. # Compute the number of ordered ways of writing `n` as the sum of 3 triangular numbers.
  6. # See also:
  7. # https://oeis.org/A008443
  8. # https://projecteuler.net/problem=621
  9. func count_sums_of_two_squares (n) {
  10. var count = 1
  11. for p,e in (n.factor_exp) {
  12. var r = p%4
  13. if (r == 3) {
  14. e.is_even || return 0
  15. }
  16. if (r == 1) {
  17. count *= (e + 1)
  18. }
  19. }
  20. return count
  21. }
  22. func count_triangular_sums (n) {
  23. 0..n.ipolygonal_root(3) -> sum_by {|u|
  24. var z = (8*(n - (u * (u + 1) / 2)) + 1)
  25. count_sums_of_two_squares(z + 1)
  26. }
  27. }
  28. say count_triangular_sums(1000) #=> 78
  29. say count_triangular_sums(1234) #=> 144
  30. say count_triangular_sums(10**6) #=> 2106