number_of_representations_as_sum_of_two_squares.pl 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 23 October 2017
  4. # https://github.com/trizen
  5. # Counting the number of representations for a given number `n` expressed as the sum of two squares.
  6. # Formula:
  7. # R(n) = 4 * Prod_{ p^k|n, p = 1 (mod 4) } (k + 1)
  8. # See also:
  9. # https://oeis.org/A004018
  10. # https://en.wikipedia.org/wiki/Fermat%27s_theorem_on_sums_of_two_squares
  11. use 5.020;
  12. use strict;
  13. use warnings;
  14. use experimental qw(signatures);
  15. use ntheory qw(divisors valuation factor_exp vecsum vecprod);
  16. sub r2($n) {
  17. my $count = 4;
  18. foreach my $p (factor_exp($n)) {
  19. my $r = $p->[0] % 4;
  20. if ($r == 3) {
  21. $p->[1] % 2 == 0 or return 0;
  22. }
  23. if ($r == 1) {
  24. $count *= $p->[1] + 1;
  25. }
  26. }
  27. return $count;
  28. }
  29. foreach my $n (1 .. 30) {
  30. my $count = r2($n);
  31. if ($count != 0) {
  32. say "R($n) = $count";
  33. }
  34. }
  35. __END__
  36. R(1) = 4
  37. R(2) = 4
  38. R(4) = 4
  39. R(5) = 8
  40. R(8) = 4
  41. R(9) = 4
  42. R(10) = 8
  43. R(13) = 8
  44. R(16) = 4
  45. R(17) = 8
  46. R(18) = 4
  47. R(20) = 8
  48. R(25) = 12
  49. R(26) = 8
  50. R(29) = 8