我写了这个素数筛分算法,它运行不正常。我无法在算法本身中找到错误。有人能帮助我吗?
这是它应该打印的内容:
[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
}
答案 0 :(得分:3)
它应该是“for j:= 0”而不是“for j:= i”。