Algorithms
|
|
 |

|
The last six non-zero digits of 1,000,000! are 412544. Please, keep your money.
I wrote this code to calculate your answer:
using System;
class Program
{
const ulong Target = 1000000; const ulong RoundOff = 10000000000;
static void Main(string[] args)
{
ulong factorial = 1;
for (ulong n = 1; n <= Target; n++)
{
factorial *= n;
while (factorial % 10 == 0)
{
factorial /= 10;
}
factorial %= RoundOff;
}
Console.WriteLine("{0}! (truncated) = {1}", Target, factorial);
}
}
Why it works:
When multiplying numbers, the trailing zeros at the end will not change the outcome... so I threw those out.
Also, if you are only interested in the least significant digits, then the upper-most digits will not have an effect on the outcome of the lower digits... so I threw those out.
With all the rounding, I didn't have to worry about overflow so I was able to calculate the "truncated factorials" of very large numbers iteratively.
Enjoy,
Robert C. Cartaino
modified on Wednesday, July 2, 2008 1:26 PM
|
|
|
|
 |
|
|
General
News
Suggestion
Question
Bug
Answer
Joke
Rant
Admin