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