跳到正文

个人记录

前缀LCM

来日方长约 2 分钟
原文
文章信息与版本

文章信息

发布
2018年10月24日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

题目描述

求1~n的lcm对10000019取模的结果。

输入描述

一个正整数N

输出描述

输出lcm

数据范围

对于 30%的数据,N≤10N≤10。

对于 60%的数据,N≤10,000N≤10,000,其中有10%的数据N=2333N=2333。

对于 90%的数据,N≤10,000,000N≤10,000,000。

对于 100%的数据,N≤1018N≤10^{18}。

题解

我们先不考虑最后一个数据点。

我们可以知道的是,求解几个数的lcm的本质是各个数之间质因子的互通有无。也就是说,我们要求出一个数,它能包括1~n所有的数的质因子,且质因子的幂等于所有数里的最大次幂。

于是,解法就出来了。我们可以把1e7范围内的质数全都筛出来,然后算它们在1e7范围内的最大次幂,这用math.h库里的log函数就能做到。时间复杂度是O(N)O(N)。

最后我们说最后一个点。我们发现最后一个点的N已经比模数大了。也就是说lcm是模数的倍数,直接输出0就好了。

AC代码:

C++
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#define reint register int
using namespace std;
const int mod=10000019;
int flg[mod],prim[mod],cnt,ans=1;
long long n;double kk;
int epow(int x,int y){
    int rt=1;x%=mod;
    while(y){
        if(y&1)rt=(1ll*rt*x)%mod;
        x=(1ll*x*x)%mod;y>>=1;
    }return rt%mod;
}
int main(){
    scanf("%lld",&n);
    if(n>=mod){puts("0");return 0;}
    for(reint i=2;i<=n;i++){
        if(!flg[i])prim[++cnt]=i;
        for(reint j=1;j<=cnt&&1ll*i*prim[j]<=n;j++){
            flg[i*prim[j]]=1;if(!(i%prim[j]))break;
        }
    }kk=log(n);
    for(reint i=1;i<=cnt;i++)
        ans=(1ll*ans*epow(prim[i],(int)(kk/log(prim[i]))))%mod;
    printf("%d\n",ans);
    return 0;
}
原文