1000! How many digits are there, why?

1000! =1000 * 999 * 998 *… * 2 * 1, it can be seen that 1000! is a big number.
So how to calculate 1000! The number of digits?
We know that any number can be expressed in scientific notation, such as
1234=1.234 * 10 3
If we take the logarithm of 10 on both sides of the equation, the equation becomes
log 10 (1234)=log 10 (1.234 * 10 3 ) is
equivalent to
log 10 (1234) = log 10 (1.234) + log 10 10 3 and
finally becomes
log 10 (1234) = log 10 (1.234) + 3
We find that the number of digits in 1234 is equal to 1234 Add 1 to the integer part of the logarithm of 10.
Then it can be said:
If the number N is expressed in scientific notation as: N = a * 10 n (0<a<10)
then log 10 N=log 10 (a )+ n (where 0<log 10a<1)
So the number of bits of N is equal to n+1.
So come 1000! The number of digits has an idea, it is equal to the integer part of log 10 (1000!) plus 1.
And log 10 (1000!)=log 10 (1000 * 999 * 998 *… * 2 * 1)
which is log 10 (1000!)=log 10 (1000)+log 10 (999)+…+log 10 (1 )
So that we can find its value through the loop.

#include<stdio.h>
#include<math.h>
int main()
{
    
    
	int n = 1000;
	double sum = 0.0;
	int i = 0;
	for (i = 1; i <= 1000; i++)
	{
    
    
		sum = sum + log10(i);
	}
	int ret = (int)sum + 1;
	printf("%d\n", ret);
	return 0;
}

It is worth noting that we should use double type variables to store log 10 (1000!) to ensure that the sum of 1000 decimals is accurate, otherwise the data will be lost and the result will be inaccurate.
Finally, the forced type of sum is converted to an integer and then added to 1, the output result is 1000! The number of digits is 2568 in total , if we honestly will be 1000! Calculate it, and then count its digits. That would be a lot of work. Also see the charm of the code.

Guess you like

Origin blog.csdn.net/chenlong_cxy/article/details/113181952