[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 @ 2011-01-22 14:12  周银辉  阅读(2208)  评论(7编辑  收藏  举报