rectangle_sides_from_area_and_diagonal.pl 684 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 22 January 2018
  4. # https://github.com/trizen
  5. # Formula for finding the length of the sides of a rectangle
  6. # when only its area and the length of its diagonal are known.
  7. # See also:
  8. # https://en.wikipedia.org/wiki/Fermat%27s_factorization_method
  9. use 5.010;
  10. use strict;
  11. use warnings;
  12. sub extract_rectangle_sides {
  13. my ($n, $h) = @_;
  14. my $s = (2 * $n + $h);
  15. my $x = sqrt($s - 4 * $n) / 2;
  16. my $y = sqrt($s) / 2;
  17. return ($y - $x, $x + $y);
  18. }
  19. my $p = 43;
  20. my $q = 97;
  21. my $n = $p * $q; # rectangle area
  22. my $h = $p**2 + $q**2; # diagonal length, squared
  23. say join(' ', extract_rectangle_sides($n, $h));