题解:AT_abc428_d [ABC428D] 183184

· · 题解

题解:AT_abc428_d [ABC428D] 183184

简述题意

给定两个整数 c,d,定义 f(x,y) 为把两个数字变成字符串,并将两个字符串拼在一起再转化为数字。求满足 f(c,c+x) 为完全平方数且 1\leq x\leq d 的 x 的个数。

前置

首先分析,在拼起来后大概 10^{17} 的范围内的完全平方数个数都是 10^8 级别的了,所以方法肯定是 lg 级别的算法。

做法

我们可以枚举 c+x 的位数 len,然后找到 c+x 在 len 长度的最大值 r 和最小值 l,最后用 1 到 r 的完全平方个数减去 1 到 l-1 的完全平方个数就是 c+x 的长度为 len 的 x 个数,累加起来 1\leq len\leq 10 的个数就是答案(因为 c+x 最大不超过 10^{10})。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
int t,c,d,pw,ans;
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>t;
    while(t--)
    {
        ans=0;
        pw=1;
        cin>>c>>d;
        for(int len=1;len<=10;len++)
        {
            pw*=10;
            int l=max(c*pw+pw/10,stoll(to_string(c)+to_string(c+1)));
            int r=min(c*pw+pw-1,stoll(to_string(c)+to_string(c+d)));
            if(l-1<=r)
            {
                int o=sqrt(l-1);
                while((o+1)*(o+1)<=l-1) o++;
                while(o*o>l-1) o--;//后面这两步是为了避免sqrt误差
                int p=sqrt(r);
                while((p+1)*(p+1)<=r) p++;
                while(p*p>r) p--;
                ans+=p-o;
            }
        }
        cout<<ans<<endl;
    }

    return 0;
}