CMIMC 2017 Power Problem 7

Let p be any real number in [0,1]. Using only calls to \mathbf{B}(1 / 2), devise an algorithm that terminates with probability 1 and returns a random number X \sim \operatorname{Bernoulli}(p). Prove that your algorithm is correct and terminates with probability 1. Partial credit of at most 4 points will be awarded for solving the case of p=1 / 3.