LightOj 1289 - LCM from 1 to n(LCM + 素数)
2024-10-18 03:43:44
题目链接:http://lightoj.com/volume_showproblem.php?problem=1289
题意:求LCM(1, 2, 3, ... , n)%(1<<32), (1<n<=1e8);
LCM(1, 2, 3, ... , n) = n以内所有素数的最高次幂之积,例如15: 23*32*5*7*11*13 = 36360360;
为了防止TLE所以,要有一个数组表示前缀积,但是直接开LL会MLE是,因为有个%1<<32刚好是unsigned int之内,可以开int的数组;
关于求1e8内的素数表,用bool类型也会MLE的,所以可以使用bitset类型;
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <bitset>
#include <iostream>
#include <time.h> typedef long long LL; using namespace std; const int N = 1e8+;
const double eps = 1e-;
const int INF = 0x3f3f3f3f;
const LL mod = (1ll<<); int k, p[];
unsigned int Mul[];
bitset<N> f; void Init()
{
f.reset();
for(int i=; i<N; i++)
{
if(f[i]) continue;
p[k++] = i;
for(int j=i+i; j<N; j+=i)
f[j] = ;
}
} int main()
{
int T, t = ;
scanf("%d", &T); Init(); Mul[] = p[];
for(int i=; i<k; i++)
Mul[i] = Mul[i-]*p[i]; while(T --)
{
int n; scanf("%d", &n); int pos = upper_bound(p, p+k, n)-p - ; LL ans = Mul[pos]; for(int i=; i<k && (LL)p[i]*p[i]<=n; i++)
{
LL num = ;
while(num <= n)
num *= p[i];
if(num%(p[i]*p[i]) == ) num /= (p[i]*p[i]);
ans = ans*num%mod;
} printf("Case %d: %lld\n", t++, ans);
}
return ;
}
还有一种比较快一点的方法:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <bitset>
#include <iostream>
#include <time.h> typedef long long LL; using namespace std; const int N = 1e8+;
const double eps = 1e-;
const int INF = 0x3f3f3f3f;
const LL mod = (1ll<<); int k = , p[], f[N/+];
unsigned int Mul[]; void Init()
{
p[k++] = ;
for(int i=; i<N; i+=)
{
if(f[i/]&(<<((i/)%)))
continue;
p[k++] = i;
for(int j=*i; j<N; j+=*i)
f[j/] |= (<<((j/)%));
}
///printf("%d\n", k);
} int main()
{
int T, t = ;
scanf("%d", &T); Init(); Mul[] = p[];
for(int i=; i<k; i++)
Mul[i] = Mul[i-]*p[i]; while(T --)
{
int n; scanf("%d", &n); int pos = upper_bound(p, p+k, n)-p - ; LL ans = Mul[pos]; for(int i=; i<k && (LL)p[i]*p[i]<=n; i++)
{
LL num = ;
while(num <= n)
num *= p[i];
if(num%(p[i]*p[i]) == ) num /= (p[i]*p[i]);
ans = ans*num%mod;
} printf("Case %d: %lld\n", t++, ans);
}
return ;
}
最新文章
- 分享公司DAO层动态SQL的一些封装
- 数据转移发现font有问题
- Linux使用笔记: 定制core dump文件的文件名
- 杭电ACM2076--夹角有多大(题目已修改,注意读题)
- C#基础练习(使用委托窗体传值)
- LeetCode题解——3Sum
- arm的一些概念(ARM7、Cortex-M的区别)
- shell如何生成rpm包仓库列表文件的对比结果
- Js数组的操作push,pop,shift,unshift等方法详细介绍
- Android远程桌面助手
- python开发【第一篇】
- pyqt4 写动画不能播放问题集合
- Jstorm与RocketMQ整合
- 二叉树的最大深度算法面试题-leetcode学习之旅(3)
- Java连接redis
- 怎样将virtualbox中的虚拟系统安装到c盘以外的盘
- parallels tools 安装
- 876. Middle of the Linked List
- 消息中间件系列一:入门、JMS规范、ActiveMQ使用
- Asp.Net MVC 获取当前 Controller Action Area