去和一个糟糕的质数算法

huangapple go评论84阅读模式
英文:

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 &quot;fmt&quot;

func main() {
 var primes = sieve(makeNumbers(29))
 fmt.Printf(&quot;%d\n&quot;, primes);
}

func makeNumbers(n int) []int {
 var numbers = make([]int, n - 1)
 for i := 0; i &lt; 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] &lt;= max; i++ {
  for j := i; j &lt; 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".

huangapple
  • 本文由 发表于 2011年1月9日 11:36:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/4637550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定