Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Digit Sum vs Product

Compare a positive integer's digit sum and digit product in Python. Students trace two accumulators, digit extraction, and why an unchanged copy is useful.

AdvancedPhase 1 - Level 5: Creative / Tricky Logical ScenariosExample 7 of 10
digit-sum-vs-product.py
1# Take number
2num = int(input("Enter a number (1-9999): "))
3
4# Calculate sum and product of digits
5digit_sum = 0
6digit_product = 1
7temp = num
8
9while temp > 0:
10 digit = temp % 10
11 digit_sum += digit
12 digit_product *= digit
13 temp //= 10
14
15# Compare
16if digit_sum > digit_product:
17 print("Sum is greater than product")
18elif digit_sum < digit_product:
19 print("Product is greater than sum")
20else:
21 print("Sum equals product")

Output

Enter a number (1-9999): 123
Sum equals product

Enter a number (1-9999): 234
Product is greater than sum

In this one

  • Maintain two accumulators
  • Use a disposable digit copy
  • Compare completed summaries

How it works

  1. 1

    Initialize sum zero, product one, and temp.

  2. 2

    Extract each digit and update both accumulators.

  3. 3

    Compare the completed sum and product.

Edge cases

What happens when a digit is zero?

What happens when a digit is zero?

The product becomes zero and stays zero.

What happens for input zero here?

What happens for input zero here?

The loop is skipped, leaving sum zero and product one; zero is outside the prompted range.

What's going on

One scan can calculate two different summaries of the same digits. digit_sum starts at zero, while digit_product starts at one so multiplication does not erase the result immediately.

temp % 10 extracts a digit and temp //= 10 removes it. Both summaries use each digit before removal. For 123, the sum and product are both six, so the equality branch runs. The loop assumes a positive input as prompted.

What happens when a digit is zero? The product becomes zero and stays zero.

What happens for input zero here? The loop is skipped, leaving sum zero and product one; zero is outside the prompted range.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why start the product at one?

Pick an answer to check it.

Question 2

What happens when a digit is zero?

Pick an answer to check it.

Questions people ask

What happens when a digit is zero?

The product becomes zero and stays zero.

What happens for input zero here?

The loop is skipped, leaving sum zero and product one; zero is outside the prompted range.

Why start the product at one?

One leaves the first multiplied digit unchanged.