Compute the Mertens function
Mathematica, 22 20 bytes
Thanks to @miles for saving 2 bytes.
Tr@*MoebiusMu@*Range
Explanation
Range
Generate a list from 1 to input.
MoebiusMu
Find MoebiusMu
of each number
Tr
Sum the result.
Python 2, 45 37 bytes
f=lambda n,k=2:n<k or f(n,k+1)-f(n/k)
Test it on Ideone.
Background
This uses the property
from A002321, which leads to the following recursive formula.
How it works
We use recursion not only to compute M for the quotients, but to compute the sum of those images as well. This saves 8 bytes over the following, straightforward implementation.
M=lambda n:1-sum(M(n/k)for k in range(2,n+1))
When f is called with a single argument n, the optional argument k defaults to 2.
If n = 1, n<k
yields True and f returns this value. This is our base case.
If n > 1, n<k
initially returns False and the code following or
is executed. f(n/k)
recursively computes one term of the sum, which is subtracted from the return value of f(n,k+1)
. The latter increments k and recursively calls f, thus iterating over the possible values of k. Once n < k + 1 or n = 1, f(n,k+1)
will return 1, ending the recursion.
05AB1E, 16 15 bytes
LÒvX(ygmyyÙïQ*O
Explanation
L # range [1 .. n]
Ò # list of prime factors for each in list
v # for each prime factor list
X(ygm # (-1)^len(factors)
yyÙïQ* # multiplied by factors == (unique factors)
O # sum
Try it online!