Hexagonal Numbers
Time limit2sMemory limit128 MB
Given N up to 1,000,000, compute the minimum number of hexagonal numbers (1, 6, 15, 28, ...) that sum to N.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Math, Number theory, BFS
- Solved
- No attempts yet
Problem
Hexagonal numbers can be defined by arranging points in hexagonal shapes. Let be the number of distinct points that appear when hexagons with 1, 2, ..., points on a side are drawn so that only one point overlaps.

The figure shows , , , and in order. The first six hexagonal numbers are 1, 6, 15, 28, 45, and 66.
Given a positive integer , find the minimum number of hexagonal numbers whose sum is .
Every integer greater than 1791 can be represented as the sum of four hexagonal numbers. Also, every sufficiently large number can be represented as the sum of three hexagonal numbers. For every positive integer, the minimum count is at most 6, and only 11 and 26 have minimum count 6. The largest number with answer 6 is 26, the largest number with answer 5 is 130, and the largest number with answer 4 is 146858.
Input
The first line contains the positive integer .
Output
Print the minimum number of hexagonal numbers needed to make .