If you interpret the bit mask as encoding a finite set $S = \{2^{b_i}\}$ of powers of $2$, you are precisely asking whether there exists a subset of $S$ which sums to $A$ modulo $p$. This is known as the modular subset-sum problem, and apparently there are efficient algorithms for it, for example [https://arxiv.org/pdf/2008.10577.pdf][1] [1]: https://arxiv.org/pdf/2008.10577.pdf (EDIT: The modular subset-sum problem is phrased as an existence statement, whereas you want to find an explicit subset. At least for the dynamic programming algorithm sketched in the beginning of the linked paper, which already gets you $O(dp)$ time where $d$ is the digit sum of your mask, this should not be a problem, since instead you can tag every element of the intermediate sum set $S_i$ by one choice of subset (or $B$) that gets you there. I haven't checked whether the other algorithms are similarly constructive)