我写了这个素数筛选算法,它不能正常运行。我在算法本身中找不到错误。有人可以帮我吗?
这是应该打印的内容:
[2 3 5 7 11 13 17 19 23 29]
与它实际打印的内容:
[3 5 7 11 13 17 19 23 25 29]
。
package main
import "fmt"
func main() {
var primes = sieve(makeNumbers(29))
fmt.Printf("%d\n", primes);
}
func makeNumbers(n int) []int {
var numbers = make([]int, n - 1)
for i := 0; i < len(numbers); i++ {
numbers[i] = i + 2
}
return numbers
}
func sieve(numbers []int) []int {
var numCopy = numbers
var max = numbers[len(numbers)-1]
var sievedNumbers = make([]int, 0)
for i := 0; numCopy[i]*numCopy[i] <= max; i++ {
for j := i; j < len(numCopy); j++ {
if numCopy[j] % numCopy[i] != 0 || j == i {
sievedNumbers = append(sievedNumbers, numCopy[j])
}
}
numCopy = sievedNumbers
sievedNumbers = make([]int, 0)
}
return numCopy
}
隔江千里
相关分类