number_of_representations_as_sum_of_four_squares.pl 975 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 four squares.
  6. # Formula:
  7. # R(n) = 8 * Sum_{d | n, d != 0 (mod 4)} d
  8. # See also:
  9. # https://oeis.org/A000118
  10. # https://en.wikipedia.org/wiki/Lagrange's_four-square_theorem
  11. use 5.020;
  12. use strict;
  13. use warnings;
  14. use experimental qw(signatures);
  15. use ntheory qw(is_prime divisor_sum);
  16. sub count_representations_as_four_squares($n) {
  17. my $count = 8 * divisor_sum($n);
  18. if ($n % 4 == 0) {
  19. $count -= 32 * divisor_sum($n >> 2);
  20. }
  21. return $count;
  22. }
  23. foreach my $n (1 .. 20) {
  24. say "R($n) = ", count_representations_as_four_squares($n);
  25. }
  26. __END__
  27. R(1) = 8
  28. R(2) = 24
  29. R(3) = 32
  30. R(4) = 24
  31. R(5) = 48
  32. R(6) = 96
  33. R(7) = 64
  34. R(8) = 24
  35. R(9) = 104
  36. R(10) = 144
  37. R(11) = 96
  38. R(12) = 96
  39. R(13) = 112
  40. R(14) = 192
  41. R(15) = 192
  42. R(16) = 24
  43. R(17) = 144
  44. R(18) = 312
  45. R(19) = 160
  46. R(20) = 144