• [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'的元素所对应的数组下标都是素数。这样建立素数表将会是后面很多题目的基础。

  • 相关阅读:
    【python cookbook】找出序列中出现次数最多的元素
    2018/1/21 Netty通过解码处理器和编码处理器来发送接收POJO,Zookeeper深入学习
    读《风雨20年》小感
    两个知识点的回顾(const指针和动态链接库函数dlopen)
    小试牛刀
    chmod,chown和chgrp的区别
    node.js中使用node-schedule实现定时任务
    在 Node.js 上调用 WCF Web 服务
    nodejs发起HTTPS请求并获取数据
    openstack 之~云计算介绍
  • 原文地址:https://www.cnblogs.com/zhouyinhui/p/1941952.html
Copyright © 2020-2023  润新知