The last digit of 0! or 1! is 1.
The last digit of 2! is 2.
The last digit of 3! is 6.
The last digit of 4! is 4.
The last digit of any higher factorial is ... 0.
Is there a clever way to determine the highest-order digit?
Hi dutch,
In the unlikely event this works, it would definitely go down as cheating! "Clever" it isn't!
Don't expect it to work for very big numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <sstream>
#include <cmath>
usingnamespace std;
int firstDigitOfFactorial( int N )
{
stringstream ss;
ss << tgamma( N + 1.0 );
return ss.str()[0] - '0';
}
int main()
{
for ( int i = 1; i <= 50; i++ ) cout << i << " " << firstDigitOfFactorial( i ) << '\n';
}
Well, N! is gamma(N+1), but I'm sure you knew that.
lgamma() gives the natural log of gamma, so lgamma()/log(10) will give the base-10 logarithm of gamma.
If I take 10 to the power of this then, in theory, I would get gamma(). However, the numbers would be huge and would overflow. But such numbers could be divided by 10 to any integer power p without changing the first digit; conveniently you could achieve the same by subtracting p from the logarithm before taking 10 to the power. The most convenient p to use, which keeps the resulting numbers very small, is the integer part of log10(gamma()).
I've no idea why they occur, but I'm struck by the length of some of the repeats of that first digit for successive factorials.
I guess that it's happening near powers of 10. Then the factorial is effectively being multiplied by something like 1.00abc x 10^n, so multiplying by something like 1 (times a power of 10) doesn't change the first digit.