Sum of Factorials

Given N up to 100000, find the fewest factorials (repeats allowed) whose sum equals N.

Medium5Dynamic programmingMathGreedyInterviewNo attempts yetTime limit1sMemory limit512 MB

Problem

The factorial of a positive integer NN is written N!N! and is defined as the product of every positive integer that is at most NN. For example, 4!=4×3×2×1=244! = 4 \times 3 \times 2 \times 1 = 24.

You are given a positive integer NN. Write a program that finds the smallest kk such that N=a1!+a2!++ak!N = a_1! + a_2! + \cdots + a_k!. Each aia_i is a positive integer, and the same value may appear more than once.

For N=10N = 10 the answer is 3, because 10=3!+2!+2!10 = 3! + 2! + 2! writes NN as a sum of three factorials. For N=25N = 25 the answer is 2, because 25=4!+1!25 = 4! + 1!.

Input

The first line contains an integer NN (1N1051 \le N \le 10^5).

Output

Print on one line the smallest number of factorials whose sum equals NN.