SPOJ4491 Primes in GCD Table 莫比乌斯反演+分块+前缀和

本文介绍了一种算法,用于解决一个特定的问题:计算一个由最大公约数构成的表格中素数出现的次数。该算法利用了莫比乌斯反演原理,并通过筛法预先计算关键函数值,最后采用分块技术和前缀和来优化求解过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
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

题意就是求:1<=i<=a,1<=j<=b, gcd(i,j) 为一素数p的对数,可以考虑用莫比乌斯反演去做,关键是其中一个g(x)的求法,

可以在筛法中求解,最后用分块和前缀和进行优化。



#include <iostream>
#include <cstdio>
#include <map>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define LL long long
#define maxn 10000010
bool v[maxn];
int prime[maxn],mu[maxn],g[maxn],sum[maxn];

void Moblus()
{
    memset(v,false,sizeof(v));
    mu[1]=1;
    g[1]=0;
    sum[0]=sum[1]=0;
    int tot=0;
    for(int i=2;i<=maxn;i++)
    {
        if(!v[i]){
            prime[tot++]=i;
            mu[i]=-1;
            g[i]=1;
        }
        for(int j=0;j<tot;j++){
            if(i*prime[j]>maxn) break;
            v[i*prime[j]]=true;
            if(i%prime[j]==0){
                mu[i*prime[j]]=0;
                g[i*prime[j]]=mu[i];
                break;
            }else{
                mu[i*prime[j]]=-mu[i];
                g[i*prime[j]]=mu[i]-g[i];
            }
        }
        sum[i]=sum[i-1]+g[i];
    }
}
int main()
{
    int a,b,t;
    Moblus();
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&a,&b);
        LL ans=0;
        int n=min(a,b);
        for(int i=1,last;i<=n;i=last+1){
            last=min(a/(a/i),b/(b/i));
            ans+=(LL)(a/i)*(b/i)*(sum[last]-sum[i-1]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值