doutizong8099
2019-02-16 19:07
浏览 246
已采纳

Go中的元组分配

Using this code:

for i := uint64(3); n > 1; i, n = i+2, n-1 {

The Go Playground output is:

1999993

Which is not correct result.

And this code:

func (p *Prime) Generate(n uint) {
    p.Primes = make([]uint64, 1, n)
    p.Primes[0] = 2
next:
    for i := uint64(3); n > 1; i += 2 {
        q := uint64(math.Sqrt(float64(i)))
        for _, v := range p.Primes[1:] {
            if v > q {
                break
            }
            if i%v == 0 {
                continue next
            }
        }
        p.Primes = append(p.Primes, i)
        n--
    }
}

Which uses :

for i := uint64(3); n > 1; i += 2 {

then

n--

The output is correct:

15485863

go version go1.11.5 linux/amd64

Am I missing something on tuple Assignments in Go?

Thanks in advance.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushanlv5184 2019-02-16 19:21
    已采纳

    Nope, it is not tuple assignment that gives wrong result.

    There is a subtle difference between the two code, which causes the bug. In the playgound code, i,n = i+2,n-1 makes n = n-1 runs everytimes the loop is iterated, while the github code only runs n = n-1 when i is a prime (it skips n-- if continue next runs).

    打赏 评论

相关推荐 更多相似问题