A - Digit Sum of 2x
题目:
For a positive integer x, let f(x) be the sum of its digit. For example, f(144) = 1+4+4 = 9 and f(1)=1.
You are given a positive integer N. Find the following positive integers M and x:
- The maximum positive integer M for which there exists a positive integer x such that f(x)=N and f(2x)=M.
- The minimum positive integer xx such that f(x)=N and f(2x)=M for the M above.
题目大意:
定义f(x) 等于x各位上的数字总和。
求M和x:
M: 在f(x) = N的条件下,使得f(2x) = M的值最大。
x:在f(x) = N 和 f(2x) = M的条件下,x最小是多少。
样例:
Sample Input 1
3
Sample Output 1
6
3
Sample Input 2
6
Sample Output 2
12
24
Sample Input 3
100
Sample Output 3
200
4444444444444444444444444
思路分析:
f(a + b)满足如下性质:
f(a + b) = f(a) + f(b) - 9k ( k = 用竖式计算a + b时候进位的次数 )
因为根据f(x)的定义,在加法竖式中,进位,相当于从一个数中减去10,在下一个数中加上1, 因此在竖式中每出现一次进位,都会使结果少9.
计算M:
f(x) = N
f(2x) = f(x) + f(x) = M
为了让M最大,我们要让f(a +b) = f(a) + f(b) - 9k 中的k尽可能小,根据性质,k是竖式计算a+b时候进位的次数,因此,我们只要让竖式计算中a+b的进位次数等于0,即可得到M的最大值。
f(2x) = f(x) + f(x) <= 2N, 当x中各位上的数都小于等于4,即相加时不产生进位,取得最大值M = 2N.
计算x:
首先x要满足
f(x) = N
f(2x) = M
根据计算M的时候可以知道,x的各位上的数都要满足小于等于4
为了让x最小,因此就要让位数尽可能少,位数尽可能少就要让各位上4(能取到的最大值)的数量尽可能多。
如果N不是4的倍数,那就把N取模的结果(小于4的数)放在第一位。(保证最终结果x是最小的)
代码:
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int main(){
cin >> n;
//M:
cout << 2 * n << '\n';
//x:
int t1, t2;
t1 = n / 4;
t2 = n % 4;
if(t2)cout << t2;
while(t1 --)cout << 4;
return 0;
}