LCM 埃拉托斯特尼素数筛法+位图改进

Given an integer n, you have to find

lcm(1, 2, 3, ..., n)

lcm means least common multiple. For example lcm(2, 5, 4) = 20, lcm(3, 9) = 9, lcm(6, 8, 12) = 24.

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case starts with a line containing an integer n (2 ≤ n ≤ 108).

Output

For each case, print the case number and lcm(1, 2, 3, ..., n). As the result can be very big, print the result modulo 232.

Sample Input

5

10

5

200

15

20

Sample Output

Case 1: 2520

Case 2: 60

Case 3: 2300527488

Case 4: 360360

Case 5: 232792560


题意:求1-n的最小公倍数

思路:n以前的每个素数,求出小于n的最大次方,例如LCM(10)=2^3*3^2*5*7=2520,LCM(20)=2^4*3^2*5*7=5040(自己领悟吧)

sum【i】预处理i以前每个素数相乘,再根据输入数据求素数多余的次方数(8=2^3,3是2的次方数)sum【10】=2*3*5*7*2^2*3

难点:素数打表,普通的筛法用于标记的 bool vis【1e8】会爆内存,所以上网看了一个埃拉托斯特尼筛法用 倍图优化(目前只会用不是很理解)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef unsigned int ui;
const int N=100000007;
int vis[N/32+50];
unsigned int sum[5800000];
int ans[5800000],tot=0;

void Prime ()   //筛素数,数组从0开始
{
    ans[0]=sum[0]=2;
    tot=1;
    for (int i=3;i<N;i+=2)   //扫所有奇数
        if (!(vis[i/32] & (1 << ((i/2)%16))))
        {
            ans[tot]=i;
            sum[tot]=sum[tot-1]*i;  //预处理
            tot++;
            for (int j=3*i;j<N;j+=2*i)  //改成i*i会超int范围
                vis[j/32] |= (1 << ((j/2)%16));
        }
}

ui deal(int n)
{
    int p=upper_bound(ans,ans+tot,n)-ans-1;
    ui bns=sum[p];
    for(int i=0;ans[i]*ans[i]<=n;i++)
    {
        ui t=ans[i];
        while(t*ans[i]<=n&&(t*ans[i]%ans[i]==0))
            t*=ans[i];
        if(t>1) bns*=t/ans[i];
    }
    return bns;
}

int main()
{
    Prime();
    int t,cas=1,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        printf ("Case %d: %u\n",cas++,deal(n));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值