All problems
1150MediumMathBacktracking

Adding Up the Balanced Squares

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2698Find the Punishment Number of an Integer

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A whole number i is balanced when the decimal digits of i * i can be cut into consecutive blocks whose values add up to i. For instance 9 is balanced, because 81 cuts into 8 and 1, which add to 9.

Return the total of i * i taken over every balanced i from 1 to n.

Examples

Example 1

Input
n = 9
Output
82

Below ten only 1 and 9 are balanced: 1 is its own square, and 81 cuts into 8 and 1. Their squares add to 82.

Example 2

Input
n = 2
Output
1

The square 4 cannot be cut into blocks adding to 2, so only 1 counts.

Example 3

Input
n = 45
Output
3503

The balanced numbers up to 45 are 1, 9, 10, 36 and 45. The last of them counts because 2025 cuts into 20 and 25.

Constraints

  • 1 <= n <= 1000

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def punishment_number(n: int) -> int:
Java
public int punishmentNumber(int n)
September 7
Apply