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

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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容