difference_of_two_rectangles_solutions.sf 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/ruby
  2. # Author: Trizen
  3. # Date: 18 March 2022
  4. # https://github.com/trizen
  5. # Represent an integer as a difference of two rectangles:
  6. #
  7. # n = a*b - c*d
  8. #
  9. # with a,b,c,d > 1 and a != b and c != d.
  10. # This algorithm works only for integers that can also be represented as a difference of two squares.
  11. func difference_of_two_squares_solutions(n) {
  12. n.divisors.map {|d|
  13. break if (d*d >= n)
  14. var a = d
  15. var b = n/d
  16. (a+b).is_even || next
  17. var x = (a + b)/2
  18. var y = (b - a)/2
  19. [x, y]
  20. }
  21. }
  22. func difference_of_two_rectangles_solutions(n) {
  23. var solutions = []
  24. difference_of_two_squares_solutions(n).each_2d {|x,y|
  25. var ab = []
  26. var cd = []
  27. difference_of_two_squares_solutions(x**2).each_2d {|a,b|
  28. ab << [a+b, a-b] if (a-b > 1)
  29. }
  30. difference_of_two_squares_solutions(y**2).each_2d {|c,d|
  31. cd << [c+d, c-d] if (c-d > 1)
  32. }
  33. [ab,cd].cartesian {|x,y|
  34. solutions << [x..., y...]
  35. }
  36. }
  37. return solutions.sort
  38. }
  39. var n = 420
  40. difference_of_two_rectangles_solutions(n).each_2d {|a,b,c,d|
  41. say "#{a*b - c*d} = #{a}*#{b} - #{c}*#{d}"
  42. }
  43. __END__
  44. 420 = 242*2 - 16*4
  45. 420 = 242*2 - 32*2
  46. 420 = 338*2 - 32*8
  47. 420 = 338*2 - 64*4
  48. 420 = 338*2 - 128*2
  49. 420 = 722*2 - 64*16
  50. 420 = 722*2 - 128*8
  51. 420 = 722*2 - 256*4
  52. 420 = 722*2 - 512*2
  53. 420 = 5618*2 - 208*52
  54. 420 = 5618*2 - 338*32
  55. 420 = 5618*2 - 416*26
  56. 420 = 5618*2 - 676*16
  57. 420 = 5618*2 - 1352*8
  58. 420 = 5618*2 - 2704*4
  59. 420 = 5618*2 - 5408*2