Digit-Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 53 Accepted Submission(s): 22
Problem Description
Let
S(N) be digit-sum of
N, i.e
S(109)=10,S(6)=6.
If two positive integers a,b are given, find the least positive integer n satisfying the condition a×S(n)=b×S(2n).
If there is no such number then output 0.
If two positive integers a,b are given, find the least positive integer n satisfying the condition a×S(n)=b×S(2n).
If there is no such number then output 0.
Input
The first line contains the number of test caces
T(T≤10).
The next T lines contain two positive integers a,b(0<a,b<101).
The next T lines contain two positive integers a,b(0<a,b<101).
Output
Output the answer in a new line for each test case.
Sample Input
3 2 1 4 1 3 4
Sample Output
1 0 55899
solution:
我们发现,如果一个digit是0~4,那么*2的效益是完全获得的。 如果一个digit的是5~9,那么*2后会损失9的收益。 这里解释一下为什么会损失9的收益 对于digit是5~9的,*2之后会变成两位,即10+x,而计算S(n)的时候,10只能被记为1,故损失了9 a*S(n) == b*S(2n), 我们假设有l的长度是[0,4]范围,有L的长度是[5,9]范围 那么显然满足: S(2n)=S(n)*2-L*9 替换一下—— a*S(n) == b*(2S(n)-L*9) a*S(n) == 2b*S(n) -L*9*b (2b-a)*S(n) == L*9*b 即—— 9*b:2b-a = S(n):L 也就是说,我们得到了S(n)与L的比例关系。 然后模拟一遍即可。 怎么模拟呢? 我们不妨假设答案n仅有长度为L,且每一位都是5 然后得到了把数位和sum分撒出去。 对于sum余下的数值,我们依次加到尾巴上。 如果sum最后把长度为L的字串都填充为'9'之后,还有剩余,那么在前面贪心填充。
#include<cstdio>
#include<algorithm>
using namespace std;
int num[150];
int gcd(int a, int b)
{
if (b ==0)return a;
return gcd(b, a%b);
}
int main()
{
int t, a, b;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &a, &b);
int x = 2 * b - a, y = 9 * b;
if (x < 0||y<5*x)printf("0\n");
else if (x == 0)printf("1\n");
else {
int z = gcd(x, y);
x /= z; y /= z;
if (y > 9 * x)
{
int x1 = (y - 9 * x) % 4, x2 = (y - 9 * x) / 4;
if (x1)printf("%d", x1);
for (int i = 0; i < x2; i++)
printf("4");
y = 9 * x;
}
y -= 5 * x;
int len;
for (len = 0;len<x; len++)
{
z = min(y, 4);
num[len] = 5 + z;
y -= z;
}
for (int i = len - 1; i>= 0; i--)
printf("%d", num[i]);
printf("\n");
}
}
return 0;
}