function n=LMtheorem050302_4th(alpha,d,p)
% format n=LMtheorem050302_4th(alpha,d,p)
% How many samples required to achieve a
% margin of error, d, for a binomial parameter, p
% p from the binomial distribution
% input alpha, e.g., alpha=0.05 for confidence limits
%        d     Margin of error=1/2 95%CI
%        p     optional, binomial proportion
%              if not provided, p=0.5 used
%              so that d is the maximum.
% output n     number of samples required
% Based on Larsen & Marx Theorem 5.3.2
% Reference Larsen & Marx Introduction to Mathematical Statistics, 3rd ed
% Same Theorem 5.3.2 in Larsen & Marx (2006) 4th edition, p. 373
% Written by E Gallagher, 2003, Eugene.Gallagher@umb.edu
% http://www.es.umb.edu/edgwebp.htm
% revised 10/17/2010, 10/29/10
%
% Find the p value for the cumulative standard normal distribution
Psn=(1-alpha/2); 
% For alpha=0.05, find the z value at the 0.975 percentile of the
% cumulative standard normal distribution, or 1.96
if nargin<3
    p=0.5;
    n=norminv(Psn)^2./(4*d.^2);
else
    n=norminv(Psn)^2.*p.*(1-p)./d.^2;  % see Equation 5.3.4., p 373, 4th ed
end