2025, Dec 10 07:00

Fixing inflated digit factorial sums in Python: reset the per-digit accumulator in your loop

Learn why your Python sum of digit factorials explodes: the accumulator isn't reset each iteration. See the example, the fix, and tips to avoid loop state bugs.

When you iterate over the digits of a number and accumulate factorials, an unexpectedly huge result often points to a stateful variable that wasn’t reset between iterations. In this case, the multiplier used to compute each digit’s factorial keeps growing from one digit to the next, inflating the sum beyond what the algorithm intends.

The problem

Below is a minimal example that produces a much larger total than expected because the factorial accumulator isn’t reset for each digit.

num = int(input())
acc = 0
digit = 0
fact = 1

while num != 0:
    digit = num % 10
    for k in range(1, digit + 1):
        fact = fact * k
    acc = acc + fact
    num = num // 10

print(acc)

What goes wrong

The intent is straightforward: take the last digit, compute its factorial, add it to the running total, and move on to the next digit. However, the factorial accumulator is initialized only once before the loop and then reused across all digits. That means a digit’s factorial multiplies on top of the previous digit’s result instead of starting from 1 each time. Placing the digit extraction inside the loop is appropriate because each iteration operates on a new last digit, but the factorial accumulator must also be scoped to each iteration to avoid carrying state.

Factorials do become “ridiculously large” quickly.

That observation is true in general, but in this case the inflated sum is caused by the accumulator not being reset.

The fix

Reinitialize the factorial accumulator on every pass of the loop so that each digit’s factorial is computed independently, then add it to the sum and continue.

num = int(input())
acc = 0

while num != 0:
    digit = num % 10
    fact = 1
    for k in range(1, digit + 1):
        fact = fact * k
    acc = acc + fact
    num = num // 10

print(acc)

Why this matters

State that unintentionally persists across iterations is a common source of logical errors in loops. The algorithm here hinges on isolation: each digit’s factorial must start from 1, complete, and only then be folded into the aggregate. Without resetting the accumulator, you end up computing chained products spanning multiple digits, which diverges from the intended behavior and produces oversized results.

Takeaways

Whenever a loop computes a per-item quantity like a factorial, power, or checksum component, make sure the per-item accumulator is reinitialized inside the loop. Keep the aggregate outside the loop, and keep the per-item state inside. If outputs look unexpectedly large, verify which variables retain values between iterations and which should be reset.