Click here to Skip to main content
13,193,600 members (47,927 online)


GeneralThe six rightmost non-zero digits of 1000000! Pin
Rod Gowdy2-Jul-08 4:50
memberRod Gowdy2-Jul-08 4:50 
GeneralRe: The six rightmost non-zero digits of 1000000! [modified] Pin
Robert.C.Cartaino2-Jul-08 6:33
memberRobert.C.Cartaino2-Jul-08 6:33 
The last six non-zero digits of 1,000,000! are 412544. Please, keep your money.

I wrote this code to calculate your answer:
// Calculate the least significant (non-zero) digits of large factorials.
// By Robert C. Cartaino
// Posted via
// 02-July-2008
using System;
class Program
    const ulong Target = 1000000;       // This is the number you are trying to find the factorial of.
    const ulong RoundOff = 10000000000; // This rounds off the answer so the intermediate results don't overflow.
    static void Main(string[] args)
        ulong factorial = 1;
        // Iterate through all numbers up to 'Target', multiply by each to find the factorial of 'Target'.
        for (ulong n = 1; n <= Target; n++)
            factorial *= n;
            // Remove the trailing zeros.
            while (factorial % 10 == 0)
                factorial /= 10;
            // We only need the right-most digits.
            factorial %= RoundOff;
            //Console.WriteLine("{0}! = {1}", n, factorial);
        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.


Robert C. Cartaino

modified on Wednesday, July 2, 2008 1:26 PM

GeneralRe: The six rightmost non-zero digits of 1000000! Pin
Rod Gowdy3-Jul-08 3:42
memberRod Gowdy3-Jul-08 3:42 
GeneralRe: The six rightmost non-zero digits of 1000000! Pin
Robert.C.Cartaino3-Jul-08 10:06
memberRobert.C.Cartaino3-Jul-08 10:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Advertise | Privacy |
Web01 | 2.8.171018.2 | Last Updated 16 Oct 2017
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid