Go 和一个糟糕的素数算法
我编写了这个素数筛选算法,但它无法正常运行。我找不到算法本身的错误。有人可以帮助我吗?
这是它应该打印的内容:
[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
}
I wrote this prime number sieving algorithm and it doesn't run properly. I can't find the error in the algorithm itself. Could someone help me?
This is what it's supposed to print:
[2 3 5 7 11 13 17 19 23 29]
Versus what it actually prints:
[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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它应该是“for j := 0”而不是“for j := i”。
It should be "for j := 0" rather than "for j := i".