This is a specific type of general algorithm/research area called Bernoulli Factories if anyone wants to go deep.
[1] https://peteroupc.github.io/bernoulli.html
[2] Knuth, Donald E. and Andrew Chi-Chih Yao. “The complexity of nonuniform random number generation”, in Algorithms and Complexity: New Directions and Recent Results, 1976.