SPOJ PGCD - Primes in GCD Table [莫比乌斯反演+分段+求和优化]【组合数学】

题目连接:https://vjudge.net/problem/10581/origin

——————————————————————————————–.
PGCD - Primes in GCD Table

Johnny has created a table which encodes the results of some operation – a function of two arguments. But instead of a boring multiplication table of the sort you learn by heart at prep-school, he has created a GCD (greatest common divisor) table! So he now has a table (of height a and width b), indexed from (1,1) to (a,b), and with the value of field (i,j) equal to gcd(i,j). He wants to know how many times he has used prime numbers when writing the table.

Input

First, t ≤ 10, the number of test cases. Each test case consists of two integers, 1 ≤ a,b < 10^7.

Output

For each test case write one number - the number of prime numbers Johnny wrote in that test case.

Example

Input:
2
10 10
100 100

Output:
30
2791

——————————————————————————————–.

题目大意:
问你在 {gcd(x,y)x[1,n],y[1,m]} 中素数的个数.

解题思路:
很好想到
f(d)=nx=1my=1[gcd(x,y)=p] (其中P为素数,[] 括号内式子成立为1,否则0)
F(d)=nx=1my=1[d|gcd(x,y)]F(d)=[nd][md]

显然 F(n)=d|nf(d)

两种形式反演后得到
f(d)=d|nμ(nd)F(d) (1)
f(n)=d|nμ(d)F(nd) (2)

我们取(1)式
f(d)=d|nμ(nd)[nd][md] (1)

最终结果就是

ans=min(n,m)pf(p)=min(n,m)pmin(n,m)/pd=1μ(d)[n/pd][m/pd]

直接计算复杂度太高 显然不可取。

令t = pk;
min(n,m)pmin(n,m)/pd=1μ(d)[nt][mt]=min(n,m)t=1pp<=n,p|t,pμ(tp)[nt][mt]

其中对于 pp<=n,p|t,pμ(tp) 我们可以在线性筛中预处理出来,然后求其前缀和

最后通过分段优化一下即可,

参考

难死了,看了好久都不是很懂、,(Ps:线性筛真TM强大)

附本题代码
——————————————————————————————–.

int const MAX = 1e7 + 5;
int mob[MAX], p[MAX], g[MAX], sum[MAX];
bool noprime[MAX];

int Mobius()
{
    mob[1] = 1;
    int pnum = 0;
    for(int i = 2; i < MAX; i++)
    {
        if(!noprime[i])
        {
            p[pnum ++] = i;
            mob[i] = -1;
            g[i] = 1;
        }
        for(int j = 0; j < pnum && i * p[j] < MAX; j++)
        {
            noprime[i * p[j]] = true;
            if(i % p[j] == 0)
            {
                mob[i * p[j]] = 0;
                g[i * p[j]] = mob[i];
                break; 
            }
            mob[i * p[j]] = -mob[i];
            g[i * p[j]] = mob[i] - g[i];
        }
        sum[i] = sum[i - 1] + g[i];
    }
}

ll cal(int l, int r)
{
    ll ans = 0;
    if(l > r)
        swap(l, r);
    for(int i = 1, last = 0; i <= l; i = last + 1)
    {
        last = min(l / (l / i), r / (r / i));
        ans += (ll) (l / i) * (r / i) * (sum[last] - sum[i - 1]);
    }
    return ans;
}

int main()
{
    Mobius();
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int l, r;
        scanf("%d %d", &l, &r);
        printf("%lld\n", cal(l, r));
    }  
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值