Find the Punishment Number of an Integer - Problem
Given a positive integer n, return the punishment number of n.
The punishment number is a fascinating mathematical concept that challenges us to find special integers with unique digit properties. For an integer i to contribute to the punishment number, its square must have a remarkable property: its digits can be split into contiguous groups that sum back to the original number!
Definition: The punishment number of n is the sum of squares of all integers i where:
1 ≤ i ≤ n- The decimal representation of
i²can be partitioned into contiguous substrings such that the sum of these substring values equalsi
Example: For i = 10, we have i² = 100. We can partition "100" as "1" + "00" = 1 + 0 = 1 ≠ 10, or "10" + "0" = 10 + 0 = 10 ✓. Since the sum equals the original number, 10 contributes 10² = 100 to the punishment number.
Input & Output
example_1.py — Basic Case
$
Input:
n = 10
›
Output:
182
💡 Note:
Numbers 1, 9, and 10 are punishment numbers. 1² = 1 ("1" = 1), 9² = 81 ("81" = 81 ≠ 9, "8"+"1" = 9 ✓), 10² = 100 ("10"+"0" = 10 ✓). Sum = 1 + 81 + 100 = 182.
example_2.py — Smaller Case
$
Input:
n = 37
›
Output:
1478
💡 Note:
Punishment numbers ≤ 37 are: 1, 9, 10, 36. Their squares are 1, 81, 100, 1296. For 36: 36² = 1296, and "1"+"2"+"9"+"6" = 18 ≠ 36, but "12"+"9"+"6" = 27 ≠ 36, "1"+"29"+"6" = 36 ✓. Sum = 1 + 81 + 100 + 1296 = 1478.
example_3.py — Edge Case
$
Input:
n = 1
›
Output:
1
💡 Note:
Only number 1 exists. 1² = 1, and "1" = 1, so it's a punishment number. Result = 1.
Constraints
- 1 ≤ n ≤ 1000
- The answer is guaranteed to fit in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Square Investigation
Take each number i and create its square 'fingerprint' i²
2
Digit Splitting
Try all possible ways to split the square's digits into contiguous groups
3
Sum Verification
Check if any splitting arrangement sums back to the original number i
4
Evidence Collection
If verified, add i² to the punishment number total
Key Takeaway
🎯 Key Insight: Use backtracking to systematically explore all possible digit partitions, with memoization to cache subproblem results and avoid redundant computations.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code