partial_sums_of_liouville_function.pl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 04 April 2019
  4. # https://github.com/trizen
  5. # A sublinear algorithm for computing the summatory function of the Liouville function (partial sums of the Liouville function).
  6. # Defined as:
  7. #
  8. # L(n) = Sum_{k=1..n} λ(k)
  9. #
  10. # where λ(k) is the Liouville function.
  11. # Example:
  12. # L(10^1) = 0
  13. # L(10^2) = -2
  14. # L(10^3) = -14
  15. # L(10^4) = -94
  16. # L(10^5) = -288
  17. # L(10^6) = -530
  18. # L(10^7) = -842
  19. # L(10^8) = -3884
  20. # L(10^9) = -25216
  21. # L(10^10) = -116026
  22. # OEIS sequences:
  23. # https://oeis.org/A008836 -- Liouville's function lambda(n) = (-1)^k, where k is number of primes dividing n (counted with multiplicity).
  24. # https://oeis.org/A090410 -- L(10^n), where L(n) is the summatory function of the Liouville function.
  25. # See also:
  26. # https://en.wikipedia.org/wiki/Liouville_function
  27. use 5.020;
  28. use strict;
  29. use warnings;
  30. use experimental qw(signatures);
  31. use ntheory qw(liouville sqrtint rootint);
  32. sub liouville_function_sum($n) {
  33. my $lookup_size = 2 * rootint($n, 3)**2;
  34. my @liouville_lookup = (0);
  35. foreach my $i (1 .. $lookup_size) {
  36. $liouville_lookup[$i] = $liouville_lookup[$i - 1] + liouville($i);
  37. }
  38. my %seen;
  39. sub ($n) {
  40. if ($n <= $lookup_size) {
  41. return $liouville_lookup[$n];
  42. }
  43. if (exists $seen{$n}) {
  44. return $seen{$n};
  45. }
  46. my $s = sqrtint($n);
  47. my $L = $s;
  48. foreach my $k (2 .. int($n / ($s + 1))) {
  49. $L -= __SUB__->(int($n / $k));
  50. }
  51. foreach my $k (1 .. $s) {
  52. $L -= $liouville_lookup[$k] * (int($n / $k) - int($n / ($k + 1)));
  53. }
  54. $seen{$n} = $L;
  55. }->($n);
  56. }
  57. foreach my $n (1 .. 9) { # takes ~2.6 seconds
  58. say "L(10^$n) = ", liouville_function_sum(10**$n);
  59. }