solution - AT_abc361_f

· · 题解

Solution

首先,b=2(合法的数可以表示成 a^2)的情况数为 \lfloor \sqrt n \rfloor 个,而样例 #2 中 \lfloor \sqrt{10^{18}} \rfloor = 10^9,但是总数只有 10^9 + 1003332 个,所以可以暴力枚举出 b \neq 2 的答案个数,然后加上 b=2 的个数即可。

需要注意的是,不可以用快速幂,因为 long long 的最大值大约是 9 \times 10^{18},但 n \le 10^{18},所以快速幂在计算过程中非常容易炸 long long。因为指数最大只有 \log_2(10^{18}) \approx 59.7,所以要直接累乘计算幂,在过程中用 double 判一下当前结果是否 >n 就可以。

还有,不可以用 cmath 里的 sqrt,因为这样虽然可以过掉样例 #2,但是你会 WA 一个点,只能手写个开方向下取整了。

Code

#include<iostream>
#include<cstdio>
#include<set>
#define ll long long
#define il inline
using namespace std;
ll n;
set <ll> f;
il ll spow(ll a,ll b)
{
    ll ans=1;
    double safe;
    while(b--)
    {
        safe=ans*a;
        if(safe>n) return n+1;
        ans*=a;
    }
    return ans;
}
il ll sqrt_floor(ll x)
{
    ll l=0,r=1e9+5,mid;
    while(l+1<r)
    {
        mid=(l+r)>>1;
        if(mid*mid<=x)
            l=mid;
        else
            r=mid;
    }
    return l;
}
il void solve(ll b)
{
    ll a=2,sqr,pw=spow(a,b);
    while(pw<=n)
    {
        sqr=sqrt_floor(pw);
        if(sqr*sqr!=pw) f.insert(pw);
        ++a;
        pw=spow(a,b);
    }
    return;
}
int main()
{
    ios::sync_with_stdio(0);
    ios_base::sync_with_stdio(0);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n;
    for(ll i=3;i<=60;++i) //log2(1e19)约等于59.7
        solve(i);
    cout<<sqrt_floor(n)+f.size();
    return 0;
}