Algorithm analysis
Let be equal to the smallest number of ones with which you can compose the number . Obviously, .
The number 2 can only be represented as the sum of two ones: . Therefore, . The number 3 can only be represented as the sum of three ones: . Therefore, .
The number 4 can be represented either as , or . However, in both cases, 4 ones are used. Therefore, .
Consider the sought expression, the result of which equals .
Suppose the last operation performed in it was addition. For example, let the first addend consist of ones, and the second addend consist of ones. The value of should be chosen such that the sum is minimal.
At the same time, it is enough to iterate the value of up to , since it can be assumed that the first addend is not greater than the second. Thus, the following relationship holds:
Suppose the last operation performed in it was multiplication. For example, let the first factor consist of ones, and the second factor consist of ones. This case occurs if is divisible by .
The value of should be chosen such that the sum is minimal. It is enough to iterate the value of from 2 to . The following relationship holds:
Thus
Example
Let's calculate the answer for :
The number 7 can be represented by 6 ones, namely:
int res[5001]; scanf("%d",&n); res[1] = 1; 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]; } printf("%d\n",res[n]);