您的位置:首页 > 其它

hdu 4135

2015-08-20 15:04 337 查看
求 [A,B][A,B] 内与 nn 互质的数的个数。

1≤A≤B≤1015,1≤n≤1091 \leq A \leq B \leq 10^{15},1 \leq n \leq 10^9

n≤109n \leq 10^9,所以对 nn 的质因子枚举子集,容斥原理计算。

因为 2∗3∗5∗7∗11∗13∗17∗19∗23∗29∗31>1092*3*5*7*11*13*17*19*23*29*31 > 10^9

所以 nn 的不同质因子最多 1111 个,2112^{11} 的枚举是可以承受的。

时间复杂度:O(n−−√+2p) O(\sqrt n+2^{p})~~~ ( pp 为 nn 的质因子个数 )

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <utility>
#include <iostream>
#include <algorithm>

template<class Num>void read(Num &x)
{
    char c; int flag = 1;
    while((c = getchar()) < '0' || c > '9')
        if(c == '-') flag *= -1;
    x = c - '0';
    while((c = getchar()) >= '0' && c <= '9')
        x = (x<<3) + (x<<1) + (c-'0');
    x *= flag;
    return;
}
template<class Num>void write(Num x)
{
    if(x < 0) putchar('-'), x = -x;
    static char s[20];int sl = 0;
    while(x) s[sl++] = x%10 + '0',x /= 10;
    if(!sl) {putchar('0');return;}
    while(sl) putchar(s[--sl]);
}
#define REP(__i,__start,__end) for(int __i = (__start); __i <= (__end); __i++)

const int size = 31624, add[2] = {-1, 1};
const double eps = 1e-4;

int n;
long long A, B, ans;

int prime[size], tot;

void prework()
{
    int sz = sqrt(n) + eps, tp = n;

    tot = 0;

    REP(i, 2, sz)
    {
        if(!(tp % i))
        {
            while(!(tp % i)) tp /= i;

            prime[tot++] = i;

            sz = std::min(sz, tp);
        }
    }

    if(tp != 1) prime[tot ++] = tp;
}

long long solve(long long S)
{
    long long ret = S;

    REP(i, 0, (1<<tot) - 1)
    {
        int poi = 1, cnt = 0;

        REP(j, 0, tot - 1)
            if((i >> j)&1)
            {
                poi *= prime[j];
                cnt++;
            }

        ret += (S/poi) * add[cnt&1];
    }

    return S - ret;
}

int main()
{
    int T;
#ifndef ONLINE_JUDGE
    freopen("4135.in","r",stdin);
    freopen("4135.out","w",stdout);
#endif

    read(T);

    REP(CaseNum, 1, T)
    {
        printf("Case #%d: ", CaseNum);

        read(A), read(B), read(n);

        prework();

        ans = solve(B) - solve(A - 1);

        write(ans), puts("");
    }

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: