---
title: "筛法求素数"
author: "Eastsun"
date: "2008-09-10T21:02:23Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-06-23T10:16:38Z"
id: 240339
url: "https://eastsun.iteye.com/blog/240339"
---

这属于我用于解[Project Euler](http://projecteuler.net)问题而写的数学工具的一部分。之前见[按字典顺序生成所有的排列](http://eastsun.iteye.com/admin/blogs/207614)

```java
/**
   &#Util.scala
   utils for mathematical algorithm,include:
   # get all primes below bound in order
   # generate all permutations in lexicographical order 
   @author Eastsun
*/
package eastsun.math

object Util {
    /**
       Get all primes below bound in order
    */
    def getPrimes(bound:Int):Array[int] = {
        import scala.math._
        if(bound <= 2) return Array()
        var sq = sqrt(bound-1)
        var half = (bound-1)/2
        var flags = new Array[boolean](half+1)
        var prime = 3
        while(prime <= sq){
            var idx = prime*prime/2
            while(idx <= half){
                flags(idx) = true
                idx += prime
            }
            do{
                prime += 2
            }while(flags(prime>>>1))
        }
        var count = 1
        var idx = 1
        while(idx <= half){
            if(!flags(idx)) count += 1
            idx += 1
        }
        if((bound-1)%2 == 0 && !flags(half)) count -= 1
        var primes = new Array[int](count)
        primes(0) = 2
        idx =1
        var idp = 1
        while(idp < count){
            if(!flags(idx)){
                primes(idp) = 2*idx + 1
                idp += 1
            }
            idx += 1
        }
        primes
    }
}
```