Haskell, 59 bytes
n%p|n*n<2=0|mod n p>0=n%(p+1)|r<-div n p=r+p*r%2
(%2)
Implements the recursive definition directly, with an auxiliary variable p
that counts up to search for potential prime factors, starting from 2
. The last line is the main function, which plugs p=2
to the binary function defined in the first line.
The function checks each case in turn:
- If
n*n<2
, thenn
is one of-1,0,1
, and the result is0
. - If
n
is not a multiple ofp
, then incrementp
and continue. - Otherwise, express
n=p*r
, and by the "derivative" property, the result isr*a(p)+p*a(r)
, which simplifies tor+p*a(r)
becausep
is prime.
The last case saves bytes by binding r
in a guardbinding r
in a guard, which also avoids the 1>0
for the boilerplate otherwise
. If r
could be bound earlier, the second condition mod n p>0
could be checked as r*p==n
, which is 3 bytes shorter, but I don't see how to do that.