% intlog2.m
%
%  Find P=2^I, the smallest power of 2 that is greater than or equal to 
%  a positive number X.
%
x = input ( '  Enter a positive number x: ' );

if ( x <= 0.0 )
  error ( '  Your value of X was not positive!' )
end

i = 0;
p = 1;

if ( x < 1 )

  while ( x <= p )  %  subtle reason why we want <= here...
    p = p / 2;
    i = i - 1;
  end
  i = i + 1;  %  Need to "back up" one step.
  p = p * 2;

else

  while ( p < x )
    p = p * 2;
    i = i + 1;
  end

end

fprintf ( '  intlog2(x) = %d\n', i );
fprintf ( '  Smallest power of 2 bigger than %g is %g\n', x, p );
