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