Let denote the minimum number of ones needed to represent the number . Clearly, f(1) = 1.
The number can only be represented as the sum of two ones: 2 = 1 + 1. Therefore, f(2) = 2. Similarly, the number can only be represented as the sum of three ones: 3 = 1 + 1 + 1. Hence, f(3) = 3.
The number can be written either as the sum of four ones: 4 = 1 + 1 + 1 + 1, or as a product: 4 = (1 + 1) \cdot (1 + 1). However, both representations use ones, so f(4) = 4.
Now consider an expression whose value is .
1. Suppose the last operation performed is addition. Let one term be equal to and consist of ones, and the other term be equal to n - i and consist of f(n - i) ones. Then the value of should be chosen so that the sum f(i) + f(n - i) is minimized.
At the same time, it is sufficient to iterate the value of up to , since we can assume that the first summand does not exceed the second. Thus, we obtain the following relation:
2. Suppose the last operation performed was multiplication. Assume that the first factor consists of ones, and the second factor consists of ones. This case occurs when is divisible by without remainder.
We should choose the value of such that the sum f(i) + f(n / i) is minimized. At the same time, it is sufficient to iterate over in the range from to \lfloor \sqrt{n} \rfloor. Thus, we obtain the following relation:
Therefore,
Example
Сompute the answer for n = 7:
Thus, the number can be represented using ones, namely:
Algorithm implementation
Declare an array .
int res[5001];Read the input value .
scanf("%d",&n);Initialize res[1] = 1.
res[1] = 1;Next, compute the values res[2], res[3], ..., res[n] sequentially using the formula given above.
for (i = 2; i <= n; i++)
{
res[i] = i;
for (j = 1; 2 * j < i; j++)
if (res[j] + res[i - j] < res[i]) res[i] = res[j] + res[i - j];
for (j = 2; j * j <= i; j++)
if (i % j == 0)
if (res[j] + res[i / j] < res[i]) res[i] = res[j] + res[i / j];
}Print the answer.
printf("%d\n",res[n]);