英文:
Go and a bad prime number algorithm
问题
我写了这个质数筛选算法,但它不能正常运行。我找不到算法本身的错误。有人可以帮我吗?
这是它应该打印的内容:
[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
}
答案1
得分: 3
应该是"for j := 0"而不是"for j := i"。
英文:
It should be "for j := 0" rather than "for j := i".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论