Sum of digits of a factorial

后端 未结 10 710
囚心锁ツ
囚心锁ツ 2020-12-07 10:06

Link to the original problem

It\'s not a homework question. I just thought that someone might know a real solution to this problem.

I was on

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 10:29

    Even without arbitrary-precision integers, this should be brute-forceable. In the problem statement you linked to, the biggest factorial that would need to be computed would be 1000!. This is a number with about 2500 digits. So just do this:

    1. Allocate an array of 3000 bytes, with each byte representing one digit in the factorial. Start with a value of 1.
    2. Run grade-school multiplication on the array repeatedly, in order to calculate the factorial.
    3. Sum the digits.

    Doing the repeated multiplications is the only potentially slow step, but I feel certain that 1000 of the multiplications could be done in a second, which is the worst case. If not, you could compute a few "milestone" values in advance and just paste them into your program.

    One potential optimization: Eliminate trailing zeros from the array when they appear. They will not affect the answer.

    OBVIOUS NOTE: I am taking a programming-competition approach here. You would probably never do this in professional work.

提交回复
热议问题