You can make this far faster by changing the data representation. You can represent S as a bit string so that if the i'th bit is 0 then S[i] = 1 and if the i'th bit is 1 then S[i] = -1. Lets call that bit string A. You can represent F as two bit strings B,C. If the i'th bit in B is 0 then F[i] = 0. If the i'th bit of B is 1 then if the i'th bit of C is 0 then F[i] = 1 else F[i] = -1. Now the whole thing can be expressed as parity((A & B) ^ C). The parity of a bit string can be computed efficiently with bit twiddling as well. Now the entire computation is in registers, no arrays required. The random generation is also much simpler, since we only need to generate random bit strings B,C and this is already directly what random generators give us. I wouldn't be surprised if this is 1000x faster than his Python.