I have N boxes, each of which may or may not contain a ball. I want to know how many boxes have balls by sampling the boxes in the following way.

For each box in the N boxes: I open this box with probability P

If at the end I find out K boxes have a ball, I estimate the number of boxes that have a ball in it by K/P.

My question is:

Given an error X% and a confidence interval L, how can I choose the minimal P, such that the estimate K/P is at most X% away from the ground truth with confidence level L?