[Project Euler] 来做欧拉项目练习题吧: 题目007
[Project Euler] 来做欧拉项目练习题吧: 题目007
周银辉
问题描述:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
问题分析:
如果要大量求素数的话,比较快速的方法是“筛法(sieve)”。其速度很快,但其需要知道上限,这个题目没有给,猜吧,我猜110000(实际上,110000下面有10453个素数)。
筛法求素数可以如下描述(抄自维基百科):
Eratosthenes' method:
- Create a list of consecutive integers from two to n: (2, 3, 4, ..., n).
- Initially, let p equal 2, the first prime number.
- Strike from the list all multiples of p less than or equal to n. (2p, 3p, 4p, etc.)
- Find the first number remaining on the list after p (this number is the next prime); replace p with this number.
- Repeat steps 3 and 4 until p2 is greater than n.
- All the remaining numbers in the list are prime.
参考代码:
#define SZ 110000
char buffer[SZ];
void iniBuffer()
{
buffer[0] = buffer[1] = 'F';
int p = sqrt(SZ);
int i, j;
for(i=2; i<=p; i++)
{
if(buffer[i]!='F')
{
for(j=2; j*i<SZ; j++)
{
buffer[j*i]='F';//标记其不是素数
}
}
}
}
在buffer中没有被标记为'F'的元素所对应的数组下标都是素数。这样建立素数表将会是后面很多题目的基础。
分类:
Algorithm
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?