primitive_sum_of_two_squares.pl 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 24 October 2017
  4. # https://github.com/trizen
  5. # Find a solution to x^2 + y^2 = n, for numbers `n` whose prime divisors are
  6. # all congruent to 1 mod 4, with the exception of at most a single factor of 2.
  7. # Blog post:
  8. # https://trizenx.blogspot.com/2017/10/representing-integers-as-sum-of-two.html
  9. # See also:
  10. # https://oeis.org/A008784
  11. use 5.020;
  12. use strict;
  13. use warnings;
  14. use ntheory qw(sqrtmod);
  15. use experimental qw(signatures);
  16. sub primitive_sum_of_two_squares ($p) {
  17. if ($p == 2) {
  18. return (1, 1);
  19. }
  20. my $s = sqrtmod($p - 1, $p) || return;
  21. my $q = $p;
  22. while ($s * $s > $p) {
  23. ($s, $q) = ($q % $s, $s);
  24. }
  25. return ($s, $q % $s);
  26. }
  27. foreach my $n (1 .. 100) {
  28. my ($x, $y) = primitive_sum_of_two_squares($n);
  29. if (defined($x) and defined($y)) {
  30. say "f($n) = $x^2 + $y^2";
  31. if ($n != $x**2 + $y**2) {
  32. die "error for $n";
  33. }
  34. }
  35. }
  36. __END__
  37. f(2) = 1^2 + 1^2
  38. f(5) = 2^2 + 1^2
  39. f(10) = 3^2 + 1^2
  40. f(13) = 3^2 + 2^2
  41. f(17) = 4^2 + 1^2
  42. f(25) = 4^2 + 3^2
  43. f(26) = 5^2 + 1^2
  44. f(29) = 5^2 + 2^2
  45. f(34) = 5^2 + 3^2
  46. f(37) = 6^2 + 1^2
  47. f(41) = 5^2 + 4^2
  48. f(50) = 7^2 + 1^2
  49. f(53) = 7^2 + 2^2
  50. f(58) = 7^2 + 3^2
  51. f(61) = 6^2 + 5^2
  52. f(65) = 8^2 + 1^2
  53. f(73) = 8^2 + 3^2
  54. f(74) = 7^2 + 5^2
  55. f(82) = 9^2 + 1^2
  56. f(85) = 7^2 + 6^2
  57. f(89) = 8^2 + 5^2
  58. f(97) = 9^2 + 4^2