difference_of_two_squares_solutions.sf 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 01 February 2019
  4. # https://github.com/trizen
  5. # A simple algorithm for finding all the non-negative integer solutions to the equation:
  6. #
  7. # x^2 - y^2 = n
  8. #
  9. # where `n` is known (along with its prime factorization).
  10. # Blog post:
  11. # https://trizenx.blogspot.com/2017/10/representing-integers-as-difference-of.html
  12. func difference_of_two_squares_solutions(n) {
  13. n.divisors.map {|d|
  14. break if (d*d > n)
  15. var a = d
  16. var b = n/d
  17. (a+b).is_even || next
  18. var x = (a + b)/2
  19. var y = (b - a)/2
  20. [x, y]
  21. }.flip
  22. }
  23. for n in (1..30) {
  24. var a = difference_of_two_squares_solutions(n) || next
  25. say (n, ' = ', a.map { .map{ "#{_}^2"}.join(' - ') }.join(' = '))
  26. }
  27. __END__
  28. 1 = 1^2 - 0^2
  29. 3 = 2^2 - 1^2
  30. 4 = 2^2 - 0^2
  31. 5 = 3^2 - 2^2
  32. 7 = 4^2 - 3^2
  33. 8 = 3^2 - 1^2
  34. 9 = 3^2 - 0^2 = 5^2 - 4^2
  35. 11 = 6^2 - 5^2
  36. 12 = 4^2 - 2^2
  37. 13 = 7^2 - 6^2
  38. 15 = 4^2 - 1^2 = 8^2 - 7^2
  39. 16 = 4^2 - 0^2 = 5^2 - 3^2
  40. 17 = 9^2 - 8^2
  41. 19 = 10^2 - 9^2
  42. 20 = 6^2 - 4^2
  43. 21 = 5^2 - 2^2 = 11^2 - 10^2
  44. 23 = 12^2 - 11^2
  45. 24 = 5^2 - 1^2 = 7^2 - 5^2
  46. 25 = 5^2 - 0^2 = 13^2 - 12^2
  47. 27 = 6^2 - 3^2 = 14^2 - 13^2
  48. 28 = 8^2 - 6^2
  49. 29 = 15^2 - 14^2