123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- #!/usr/bin/ruby
- # Author: Trizen
- # Date: 18 March 2022
- # https://github.com/trizen
- # Represent an integer as a difference of two rectangles:
- #
- # n = a*b - c*d
- #
- # with a,b,c,d > 1 and a != b and c != d.
- # This algorithm works only for integers that can also be represented as a difference of two squares.
- func difference_of_two_squares_solutions(n) {
- n.divisors.map {|d|
- break if (d*d >= n)
- var a = d
- var b = n/d
- (a+b).is_even || next
- var x = (a + b)/2
- var y = (b - a)/2
- [x, y]
- }
- }
- func difference_of_two_rectangles_solutions(n) {
- var solutions = []
- difference_of_two_squares_solutions(n).each_2d {|x,y|
- var ab = []
- var cd = []
- difference_of_two_squares_solutions(x**2).each_2d {|a,b|
- ab << [a+b, a-b] if (a-b > 1)
- }
- difference_of_two_squares_solutions(y**2).each_2d {|c,d|
- cd << [c+d, c-d] if (c-d > 1)
- }
- [ab,cd].cartesian {|x,y|
- solutions << [x..., y...]
- }
- }
- return solutions.sort
- }
- var n = 420
- difference_of_two_rectangles_solutions(n).each_2d {|a,b,c,d|
- say "#{a*b - c*d} = #{a}*#{b} - #{c}*#{d}"
- }
- __END__
- 420 = 242*2 - 16*4
- 420 = 242*2 - 32*2
- 420 = 338*2 - 32*8
- 420 = 338*2 - 64*4
- 420 = 338*2 - 128*2
- 420 = 722*2 - 64*16
- 420 = 722*2 - 128*8
- 420 = 722*2 - 256*4
- 420 = 722*2 - 512*2
- 420 = 5618*2 - 208*52
- 420 = 5618*2 - 338*32
- 420 = 5618*2 - 416*26
- 420 = 5618*2 - 676*16
- 420 = 5618*2 - 1352*8
- 420 = 5618*2 - 2704*4
- 420 = 5618*2 - 5408*2
|