HDU 6169 Senior PanⅡ(数论+dp)

202 篇文章 1 订阅
201 篇文章 10 订阅

Description

给出一个区间 [L,R] [ L , R ] ,问该区间中所有以 K K 作为最小因子(大于1的)的数字之和

Input

第一行输入一整数 T T 表示用例组数,每组用例输入三个整数L,R,K (1LR1011,2K1011) ( 1 ≤ L ≤ R ≤ 10 11 , 2 ≤ K ≤ 10 11 )

Output

对于每组用例,输出答案,结果模 109+7 10 9 + 7

Sample Input

2
1 20 5
2 6 3

Sample Output

Case #1: 5
Case #2: 3

Solution

显然 k k 需要是素数,否则不存在数字以K为最小因子,且如果 K K N的因子,那么 N/K N / K 也是 N N 的因子,进而有KN/K,故 KN K ≤ N ,即如果 K>1011320000 K > 10 11 ≈ 320000 时,至多有一个数字(即 K K 本身)以K为最小因子,当 K320000 K ≤ 320000 时,只需解决 1 1 ~N中以 K K 为最小素因子的数字之和即可

考虑dp,以 dp[i][j] d p [ i ] [ j ] 表示前 i i 个数字中没有以前j个素数为最小素因子的数字之和,假设 K K 是第pos+1个因子,如果一个数字 X X K为最小素因子,那么 X/K X / K 必然不以前 pos p o s 个素数为最小素因子,反之,如果 Y Y 不以前pos个素因子为最小素因子,则 YK Y K 必然以 K K 为最小素因子,那么我们只要求1~ NK ⌊ N K ⌋ 中没有以前 pos p o s 个素数为最小素因子的数字之和,乘上 K K 即为1~ N N 中以K为最小素因子的数字之和,且同理可以得到转移方程,前 i i 个数字中不以前j个素数为最小素因子的数字之和 = = i个数字中不以前 j1 j − 1 个素数为最小素因子的数字之和 i个数字中以第 j j 个素数为最小素因子的数字之和,即dp[i][j]=dp[i][j1]pjdp[ipj][j1]

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define M 320000
#define mod 1000000007
#define inv2 500000004
#define A 8000
#define B 1000
int res=0,p[M+5],mark[M+5],dp[A+5][B+5];
int ins(int x,int y)
{
    return x+y>=mod?x+y-mod:x+y;
}
int des(int x,int y)
{
    return x-y<0?x-y+mod:x-y;
}
void init()
{
    for(int i=2;i<=M;i++)
        if(!mark[i])
        {
            p[++res]=i;
            for(int j=2*i;j<=M;j+=i)mark[j]=1;
        }
    dp[0][0]=0;
    for(int i=1;i<=A;i++)
    {
        dp[i][0]=ins(dp[i-1][0],i);
        for(int j=1;j<=B;j++)
            dp[i][j]=des(dp[i][j-1],(ll)p[j]*dp[i/p[j]][j-1]%mod);
    }
}
bool check(ll n)
{
    if(n<=M)return mark[n]^1;
    for(int i=1;i<=res&&(ll)p[i]*p[i]<=n;i++)
        if(n%p[i]==0)return 0;
    return 1;
}
int Solve(ll n,int m)
{
    if(n<2)return n;
    if(m==0)
    {
        n%=mod;
        return n*(n+1)%mod*inv2%mod;
    }
    if(n<=A&&m<=B)return dp[n][m];
    if(n<=p[m])return 1;
    return des(Solve(n,m-1),(ll)p[m]*Solve(n/p[m],m-1)%mod);
}
int main()
{
    init();
    int T,Case=1;
    scanf("%d",&T);
    while(T--)
    {
        ll L,R,K;
        scanf("%I64d%I64d%I64d",&L,&R,&K);
        printf("Case #%d: ",Case++);
        if(!check(K))printf("0\n");
        else if(K>M)
        {
            if(K>=L&&K<=R)printf("%d\n",K%mod);
            else printf("0\n");
        }
        else
        {
            int pos=1;
            while(p[pos]<K)pos++;
            pos--;
            int ans=des(K*Solve(R/K,pos)%mod,K*Solve((L-1)/K,pos)%mod);
            printf("%d\n",ans);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值