Gym - 101982B Coprime Integers(容斥原理)

#include
using namespace std;
typedef long long ll;
ll ans, p = 0, maxx, a, b, c, d;
ll prim[10000007],num[10000005];
void dfs(ll x, ll sum, ll num)
{

    if(num > maxx)return;
    if(sum > b || sum > d)return ;
    if(num % 2 == 1){ans += (b / sum - (a - 1) / sum) * (d / sum - (c - 1) / sum);}
    if(num % 2 == 0){ans -= (b / sum - (a - 1) / sum) * (d / sum - (c - 1) / sum);}
    for(ll i = x + 1; i <= p; i++)
    {
        ll xxx = sum * prim[i];
        if(xxx > b || xxx > d)return;
        dfs(i, xxx, num + 1);
    }
    return ;
}
void getnum(ll n)
{

    ll i, j;
    for(i = 2; i <= n; i++)
    {
        if(num[i] == 0)
        {
            num[i] = i;
            prim[++p] = i;
        }
        for(j = 1; j <= p; j++)
        {
            if(prim[j] > num[i] || prim[j] > n / i)break;
            num[i * prim[j]] = prim[j];
        }
    }
}
int main()
{
    scanf("%lld %lld %lld %lld", &a, &b, &c, &d);
    maxx = max(b, d);
    getnum(maxx);
    ans = 0;
    ll i;
    for(i = 1; i <= p; i++)
    {
        if(prim[i] > b || prim[i] > d)break;
        dfs(i, prim[i], 1);
    }
    printf("%lld\n", (b - a + 1) * (d - c + 1) - ans);
    return 0;
}

 

你可能感兴趣的:(容斥)