hdu5317 RGCDQ (质因子种数+预处理)

本文介绍了一种称为RGCDQ的问题,旨在寻找区间[L,R]内两个数的最大公因数的最大值,其中每个数的质因子种类数量作为比较的对象。通过预处理和使用空间换取时间的方法,提出了一种高效的解决方案。

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

RGCDQ

题意:F(x)表示x的质因子的种数。给区间[L,R],求max(GCD(F(i),F(j)) (L≤i<j≤R)。(2<=L < R<=1000000)

 

题解:可以用素数筛求质因子种数(这不用多说,看下代码init()中内容就能理解)。然而R的范围太大,会TLE。因此只能用空间换时间了。

可以用一个二维数组num[i][j] 保存x<=i&&F(x)=j的x的个数。(预处理,有点dp的思想)

2*3*5*7*11*13*17 > 10 ^ 6,即在1~1e6的范围内最多有7个素数相乘。so F(x)最大为7,即j<=7。

给出L,R,则num[R][j]-num[L][j]为在[L,R]区间F(x)==j的x的个数b[j]。根据b[j]的值,很容易人工求出答案。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1e6+5;
 
int f[N],num[N][10],b[10];
void init()                  //筛选法求f(x)
{
    memset(f,0,sizeof(f));
    for(int i=2;i<N;i++)
    {
        if(f[i]==0)
        {
            f[i]=1;
            for(int j=i+i;j<N;j+=i)
            {
                f[j]++;
            }
        }
    }
    for(int i=2;i<N;i++)
    {
        for(int j=1;j<8;j++)
        {
            num[i][j]=num[i-1][j];
        }
        num[i][f[i]]++;
    }
}
 
int main()
{
    int t,l,r;
    init();
    cin>>t;
    while(t--)
    {
        scanf("%d%d",&l,&r);
        int ans=0;
        for(int i=1;i<8;i++)
        {
            b[i]=num[r][i]-num[l-1][i];
            if(num[r][i]-num[l-1][i]>1)
                ans=i;
        }
        if(ans!=0)
            printf("%d\n",ans);
        else if((b[2]>0&&b[4]>0)||(b[2]>0&&b[6]>0)||(b[6]>0&&b[4]>0))
            printf("2\n");
        else if(b[3]>0&&b[6]>0)
            printf("3\n");
        else
            printf("1\n");
    }
    return 0;
}


RGCDQ

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2539    Accepted Submission(s): 1012

Problem Description

Mr. Hdu is interested in Greatest Common Divisor (GCD). He wants to find more and more interesting things about GCD. Today He comes up with Range Greatest Common Divisor Query (RGCDQ). What’s RGCDQ? Please let me explain it to you gradually. For a positive integer x, F(x) indicates the number of kind of prime factor of x. For example F(2)=1. F(10)=2, because 10=2*5. F(12)=2, because 12=2*2*3, there are two kinds of prime factor. For each query, we will get an interval [L, R], Hdu wants to know maxGCD(F(i),F(j)) (L≤i<j≤R)

Input

There are multiple queries. In the first line of the input file there is an integer T indicates the number of queries.
In the next T lines, each line contains L, R which is mentioned above.
All input items are integers.
1<= T <= 1000000
2<=L < R<=1000000

Output

For each query,output the answer in a single line.
See the sample for more details.

Sample Input

2 2 3 3 5

Sample Output

1 1



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值