Subtract the Product and Sum of Digits of an Integer
Problem
Take a positive integer n (1 ≤ n ≤ 10⁵) and look at its decimal digits. Multiply all the digits together to get a product, add them all up to get a sum, and return product − sum.
n = 23415def subtract_product_and_sum(n):
product, total = 1, 0
while n > 0:
d = n % 10
product *= d
total += d
n //= 10
return product - total
function subtractProductAndSum(n) {
let product = 1, sum = 0;
while (n > 0) {
const d = n % 10;
product *= d;
sum += d;
n = Math.floor(n / 10);
}
return product - sum;
}
int subtractProductAndSum(int n) {
int product = 1, sum = 0;
while (n > 0) {
int d = n % 10;
product *= d;
sum += d;
n /= 10;
}
return product - sum;
}
int subtractProductAndSum(int n) {
int product = 1, sum = 0;
while (n > 0) {
int d = n % 10;
product *= d;
sum += d;
n /= 10;
}
return product - sum;
}
Explanation
The whole problem is one pass over the digits of n. The key idea is that you never need the digits as a list or a string: arithmetic alone peels them off one at a time. n % 10 reads the last digit, and integer division n // 10 drops it, so a simple loop visits every digit exactly once.
We keep two accumulators while peeling. product starts at 1 — the multiplicative identity, so the first digit multiplies in cleanly — and sum starts at 0, the additive identity. Each iteration extracts d, does product *= d and sum += d, then shrinks n. When n reaches 0 there are no digits left, and the answer is just product − sum.
Walking through the default example n = 234: first peel 4, giving product = 1·4 = 4 and sum = 0+4 = 4, leaving n = 23. Then peel 3, giving product = 12 and sum = 7, leaving n = 2. Finally peel 2, giving product = 24 and sum = 9, leaving n = 0. The loop exits and we return 24 − 9 = 15.
Note that the digits come out in reverse order (least significant first), but that is harmless here: both multiplication and addition are commutative, so the order in which digits are folded into product and sum does not change the result.
An alternative is to convert n to a string and iterate over its characters, which is the same single pass with extra allocation. The arithmetic version is just as short and avoids the conversion entirely.
The loop runs once per digit, and a number n has ⌊log₁₀ n⌋ + 1 digits, so the time is O(log n). We only ever store two counters and the shrinking copy of n, so the space is O(1).