Digit-Sum
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65535/32768 K (Java/Others)
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.
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).
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
Reference Code
#include <cstdio>
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
scanf("%d",&t);
while (t--){
int a,b;
scanf("%d%d",&a,&b);
if(a==b*2){printf("1\n");continue;}
if(a>b*2||b>5*a){printf("0\n");continue;}
int tmp,Sn;
tmp=(2*b-a)/__gcd((2*b-a),9*b);
Sn=9*b/__gcd((2*b-a),9*b);
if(Sn>=9*tmp){
int ac=Sn-9*tmp;
if(ac%4)printf("%d",ac%4);
for(int i=0;i<ac/4;i++)printf("4");
for(int i=0;i<tmp;i++)printf("9");
printf("\n");
}
else{
int ac=Sn-tmp*5;
int num_9=ac/4;
int num_5=tmp-num_9;
if(5*num_5+9*num_9<Sn)num_5--;
if(num_5+num_9==tmp){
for(int i=0;i<num_5;i++)printf("5");
for(int i=0;i<num_9;i++)printf("9");
printf("\n");
}
else{
for(int i=0;i<num_5;i++)printf("5");
printf("%d",ac%4+5);
for(int i=0;i<num_9;i++)printf("9");
printf("\n");
}
}
}
return 0;
}
Tips
题意:
设函数
S
(
n
)
S(n)
S(n) 为
n
n
n 各位数字之和。现给出
a
,
b
a,b
a,b,求解满足
a
×
S
(
n
)
=
b
×
S
(
2
n
)
a\times S(n)=b\times S(2n)
a×S(n)=b×S(2n)的最小正整数
n
n
n ,若无解输出
0
0
0 。
解法:
- 很容易发现,当位上的数字 0 ⩽ i ⩽ 4 0\leqslant i\leqslant4 0⩽i⩽4 时,它对 S ( n ) S(n) S(n) 的贡献是 i i i ,对 S ( 2 n ) S(2n) S(2n) 的贡献是 2 i 2i 2i ,当 5 ⩽ j ⩽ 9 5\leqslant j\leqslant 9 5⩽j⩽9 时,它对 S ( 2 n ) S(2n) S(2n) 的贡献是 2 j − 9 2j-9 2j−9 。设 j j j 的总数量为 t t t ,则显然有 S ( 2 n ) = 2 S ( n ) − 9 t S(2n)=2S(n)-9t S(2n)=2S(n)−9t
- 代入 S ( 2 n ) S ( n ) = a b \frac{S(2n)}{S(n)}=\frac{a}{b} S(n)S(2n)=ba 解出 S ( n ) S(n) S(n) 和 t t t 为 S ( n ) t = 9 b 2 b − a \frac{S(n)}{t}=\frac{9b}{2b-a} tS(n)=2b−a9b
- 因为要令 n n n 的值尽可能的小,所以要将 S ( n ) S(n) S(n) 和 t t t 的比值化到最简,即 S ( n ) = 9 b gcd ( 9 b , 2 b − a ) S(n)=\frac{9b}{\gcd(9b,2b-a)} S(n)=gcd(9b,2b−a)9b t = 2 b − a gcd ( 9 b , 2 b − a ) t=\frac{2b-a}{\gcd(9b,2b-a)} t=gcd(9b,2b−a)2b−a
- 此时得到了大于
5
5
5 的位的个数,以及
S
(
n
)
S(n)
S(n) 。分两种情况:含有
1
∼
4
1\sim4
1∼4 的位以及不含有
1
∼
4
1\sim4
1∼4 的位。
含有:显然此时 5 ∼ 9 5\sim9 5∼9 的位应该全为 9 9 9 ,证明略。只要在 9 9 9 前面加 4 4 4 直到不够 4 4 4 ,把最后剩下来的数加到最前面。
不含有:首先将 t t t 位都赋为 5 5 5 ,若 S ( n ) S(n) S(n) 还有剩余,就从个位开始加,直到加到 9 9 9 ,然后再加到十位,以此类推。 - 无解的情况:从式子 S ( 2 n ) / S ( n ) = a / b S(2n)/S(n)=a/b S(2n)/S(n)=a/b 出发。在 1 ∼ 9 1\sim9 1∼9 中,贡献比最大的数为 1 ∼ 4 1\sim4 1∼4 , 2 2 2 倍;贡献比最低的数为 5 5 5 , 0.2 0.2 0.2 倍,于是 a > 2 b a>2b a>2b 或 b > 5 a b>5a b>5a 时无解,其他情况都有解。