function balls ( n )

%*****************************************************************************80
%
%% BALLS simulates a problem involving numbered balls in an urn.
%
%  Discussion:
%
%    An urn contains N numbered balls.  A ball is drawn repeatedly from the
%    urn, examined, and replaced.  This file calculates:
%    (1) E(n), the average number of drawings (with replacement) of numbered 
%        balls before a repetition occurs;
%    (2) T, the largest number of drawings that still allows
%        the probability there is NOT a repetition is still greater than 1/2.
%
%  Example:
%
%          N      E(N)     T
%
%         10    3.6602     4
%        100   12.2100    12
%      1,000   39.3032    37
%     10,000  124.9991   118
%    100,000  395.9997   372
%
%  Modified:
%
%    25 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
%  Input parameters:
%
%    Input, integer N, the number of balls in the urn.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BALLS:\n' );
  fprintf ( 1, '  An urn contains N numbered balls.  A ball is drawn repeatedly from the\n' );
  fprintf ( 1, '  urn, examined, and replaced.  This file calculates:\n' );
  fprintf ( 1, '  (1) E(n), the average number of drawings (with replacement) of numbered \n' );
  fprintf ( 1, '    balls before a repetition occurs;\n' );
  fprintf ( 1, '  (2) T, the largest number of drawings that still allows\n' );
  fprintf ( 1, '    the probability there is NOT a repetition is still greater than 1/2.\n' );

  F = 1 / n;
  E = F;
  j = 1;
  NF = F * ( n - j ) / n;
  while ( NF > 0 )
    F = NF;
    j = j + 1;
    NF = F * ( n - j ) / n;
    E = E + j * j * F;
  end
  fprintf ( '\n' );
  fprintf ( '  E = %g\n', E );

  j = 0;
  Prod = 1;
  while ( Prod > 0.5 )
    Prod = Prod * ( ( n - j ) / n );
    j = j + 1;
  end
  T = j - 1;
  fprintf ( '  T = %d\n', T );

  return
end
