Hexagonal Numbers

Time limit2sMemory limit128 MB

Summary
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 hnh_n be the number of distinct points that appear when hexagons with 1, 2, ..., nn points on a side are drawn so that only one point overlaps.

The figure shows h1h_1, h2h_2, h3h_3, and h4h_4 in order. The first six hexagonal numbers are 1, 6, 15, 28, 45, and 66.

Given a positive integer NN, find the minimum number of hexagonal numbers whose sum is NN.

NMinimum countSum
111
221+1
331+1+1
441+1+1+1
551+1+1+1+1
616
721+6
831+1+6
941+1+1+6
1051+1+1+1+6
1161+1+1+1+1+6
1226+6

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 NN.

Output

Print the minimum number of hexagonal numbers needed to make NN.

Constraints

  • 1≤N≤1,000,0001 \le N \le 1,000,000

Examples6

  1. Example 1

    Input
    26
    
    Expected output
    6
    
  2. Example 2

    Input
    130
    
    Expected output
    5
    
  3. Example 3

    Input
    146858
    
    Expected output
    4
    
  4. Example 4

    Input
    999999
    
    Expected output
    3
    
  5. Example 5

    Input
    1000000
    
    Expected output
    2
    
  6. Example 6

    Input
    145530
    
    Expected output
    1