Counting primitive bit strings

A string of bits is called primitive if it is not the repetition of several copies of a smaller string of bits. For example, the 101101 is not primitive because it can be broken down into two copies of the string 101. In Python notation, you could produce 101101 by "101"*2. The string 11001101, on the other hand, is primitive. (It contains substrings that are not primitive, but the string as a whole cannot be factored into multiple copies of a single string.)

For a given n, let’s count how many primitive bit strings there are of length n. Call this f(n). There are 2n bit strings of length n, and f(n) of these are primitive. For example, there are f(12) primitive bit strings of length 12. The strings that are not primitive are made of copies of primitive strings: two copies of a primitive string of length 6, three copies of a primitive string of length 4, etc. This says

and in general

Here the sum is over all positive integers d that divide n.

Unfortunately this formula is backward. It gives is a formula for something well known, 2n, as a sum of things we’re trying to calculate. The Möbius inversion formula is just what we need to turn this formula around so that the new thing is on the left and sums of old things are on the right. It tells us that

def eval(cls, n):
if n.is_integer:
if n.is_positive is not True:
raise ValueError("n should be a positive integer")
else:
raise TypeError("n should be an integer")
if n.is_prime:
return S.NegativeOne
elif n is S.One:
return S.One
elif n.is_Integer:
a = factorint(n)
if any(i > 1 for i in a.values()):
return S.Zero
return S.NegativeOne**len(a)

It looks like it’s not more efficient. As far as I know, SymPy’s factorint() doesn’t support streaming factors. That would be a useful feature, although it really only matters if you are dealing with numbers with very large prime factors (e.g., the algorithm in factorint() does trial division on primes up to 2^15 before it even gets into the Pollard rho algorithm).

An advantage of the SymPy function is that it works symbolically, i.e., you can put symbolic values in like mobius(n) and do manipulation on them and substitute them later

There was a question on StackOverflow a few months ago about determining whether a string is primitive or not, but I can’t find it. It basically duplicated the string and checked all cyclic patterns of it to see if any is repeated at all. Pretty neat to find the number of them though!