There is a simple relationship between the base b
logarithm of a number and the base b
representation of that number:
len(repr(x, b)) = 1 + floor(log(x, b))
In particular, in base 10, the number of digits in x is 1 + floor(log10(x))
. (To see why that's the case, look at the result of that formula for powers of 10.)
Now, the logarithm of a×b
is the sum of the logarithms of a
and b
. So the logarithm of n!
is simply the sum of the logarithms of the integers from 1 to n
. If we do that computation in base 10, then we can easily extract the length of the decimal expansion of n!
.
In other words, if you sum the log10
of each value instead of the log
, then you can get rid of:
fact = (exp(sum));
and
while(fact!=0)
{
dig = ((int)fact%10);
count++;
fact = floor(fact/10);
}
and just output 1 + floor(sum)
.
In theory, that could suffer from a round-off error. However, you'd need to do an awful lot of logarithms in order for the error term to propagate enough to create an error in the computation. (Not to say it can't happen. But if it happens, n
is a very big number indeed.)