works when q, p are powers of two