HDU 5710 digit sum

Title:

Define S(N) as the sum of the digits in each digit of the number N.
Given two numbers a, b, find the smallest positive integer n such that a×S(n)=b×S(2n).

analyze:

For us to find the smallest value of n that satisfies a * S(n) = b S(2n), first of all, the first idea must be violent.. But violence is definitely wrong... For example ---> 2 3 output 5589
means that the idea of ​​​​from the whole (a number) to the part (each number of digits) is not feasible, because it is a digit, so you can try to construct from the part to the whole.
So how to construct it? From if there is no S(2n) then our construction must be from low to high.
But if there is S(2n), can a certain law be constructed based on S(N) and S(2N).
There is no information given in the title, because it is to find the structure law, so it is necessary to study the number of digits of 2.
It is easy to find that when the number of digits belongs to [0, 4]
, the contribution value of each digit after 2 n will double. The difference is that the contribution value of each digit when [5, 9] is 2 n-9
Let cnt be n
S(2
n) = 2*S(n)-9cnt with each number of digits greater than or equal to 5,
then we can sort out
9b:2b-a=S(n):cnt
Then we can get S(n) as 9b If cnt is 2b-a
, then now it becomes that we already know how much S(n) and cnt are to find the smallest N
, so fill in it greedily
(fill in first and then fill in 9) and
then fill in... front ...
there are several special judgments
1.2ba=0, when S is any value, it must be satisfied, then n=1 can be output;
2.a>2b does not exist
3.a<2b must satisfy b<=5a

#include  <bits/stdc++.h>
using namespace std;
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int a,b;
        cin >> a >> b;
        int cnt = 2*b-a;
        int s = b*9;
        if(a == 2*b)
        {
            cout << 1 <<endl;
            continue;
        }
        if(a>2*b||5*a<b)
        {
            cout<< 0 <<endl;
            continue;
        }
        int gcd = __gcd(cnt,s);
        cnt/=gcd;
        s/=gcd;
        string ans=string(cnt,'5');
        //看别人代码学到的操作这个函数很好用呀
        //cout<<ans<<endl;
        s-=5*cnt;
        int val;
        for(int i=ans.size()-1;i>=0;i--)
        {
            val=min(s,4);
            ans[i]+=val;
            s-=val;
        }
        while(s)
        {
            val=min(s,4);
            ans=char(val+'0')+ans;
            s-=val;
        }
        cout<<ans<<endl;
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325033539&siteId=291194637