Find the Punishment Number of an Integer - Problem

Given a positive integer n, return the punishment number of n.

The punishment number of n is defined as the sum of the squares of all integers i such that:

  • 1 <= i <= n
  • The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.

Input & Output

Example 1 — Basic Case
$ Input: n = 10
Output: 182
💡 Note: Numbers 1, 9, 10 satisfy the condition: 1²=1 ("1"→1), 9²=81 ("8"+"1"→9), 10²=100 ("10"+"0"→10 or "1"+"00" invalid). Sum: 1+81+100=182
Example 2 — Small Input
$ Input: n = 37
Output: 1478
💡 Note: All valid numbers up to 37 whose squares can be partitioned to sum back to the original number

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
Find Punishment Number: n=1012-89101²=1→1✓No valid81→8+1=9✓100→10+0=10✓Check Each Number i:1. Calculate square = i × i2. Try all partitions of square digits using backtrackingResult: 1² + 9² + 10² = 1 + 81 + 100 = 182
Understanding the Visualization
1
Input
Given n=10, check numbers 1 through 10
2
Process
For each i, check if i² digits can partition to sum to i
3
Output
Sum of all valid i² values
Key Takeaway
🎯 Key Insight: Use backtracking to explore all possible ways to partition the square's digits into substrings that sum to the original number
Asked in
Google 15 Microsoft 10
8.5K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen