[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:

  1. Create a list of consecutive integers from two to n: (2, 3, 4, ..., n).
  2. Initially, let p equal 2, the first prime number.
  3. Strike from the list all multiples of p less than or equal to n. (2p, 3p, 4p, etc.)
  4. Find the first number remaining on the list after p (this number is the next prime); replace p with this number.
  5. Repeat steps 3 and 4 until p2 is greater than n.
  6. 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'的元素所对应的数组下标都是素数。这样建立素数表将会是后面很多题目的基础。

 

 

 

posted @   周银辉  阅读(2214)  评论(7编辑  收藏  举报
编辑推荐:
· 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,谁才是开发者新宠?
点击右上角即可分享
微信分享提示