m***@gmail.com
2015-07-30 06:26:12 UTC
I implemented one of the Project Euler problems, problem 14, in Go. If I
run it with 4 goroutines it works fine, but if I run it with 8 goroutines,
it gets the wrong answer. So far I haven't been able to see why. Here's my
code:
package main
import (
"fmt"
"runtime"
)
func steps(n uint64) uint64 {
if n == 0 { return 0 }
if n == 1 { return 0 }
var steps uint64
var i = n
for i != 1 {
for (i & 1) == 1 {
i = ((3 * i) + 1) / 2
steps += 2
}
for (i & 1) == 0 {
i /= 2
steps++
}
}
return steps
}
func maxStart(start, end uint64, result chan uint64) {
var max uint64
var maxStart uint64
for i := start; i < end; i++ {
steps := steps(i)
if steps > max {
max = steps
maxStart = i
}
}
result <- maxStart
}
func main() {
const MAX = 1000000
const GOROUTINES = 4
const PER_GOROUTINE = MAX / GOROUTINES
runtime.GOMAXPROCS(runtime.NumCPU())
results := make(chan uint64)
var current uint64
for i := 0; i < GOROUTINES; i++ {
go maxStart(current, current + PER_GOROUTINE, results)
current += PER_GOROUTINE
}
var maxStart uint64
for i := 0; i < GOROUTINES; i++ {
start := <-results
if start > maxStart {
maxStart = start
}
}
fmt.Println(maxStart)
}
Surely I am being stupid? Ideas? Thanks!
run it with 4 goroutines it works fine, but if I run it with 8 goroutines,
it gets the wrong answer. So far I haven't been able to see why. Here's my
code:
package main
import (
"fmt"
"runtime"
)
func steps(n uint64) uint64 {
if n == 0 { return 0 }
if n == 1 { return 0 }
var steps uint64
var i = n
for i != 1 {
for (i & 1) == 1 {
i = ((3 * i) + 1) / 2
steps += 2
}
for (i & 1) == 0 {
i /= 2
steps++
}
}
return steps
}
func maxStart(start, end uint64, result chan uint64) {
var max uint64
var maxStart uint64
for i := start; i < end; i++ {
steps := steps(i)
if steps > max {
max = steps
maxStart = i
}
}
result <- maxStart
}
func main() {
const MAX = 1000000
const GOROUTINES = 4
const PER_GOROUTINE = MAX / GOROUTINES
runtime.GOMAXPROCS(runtime.NumCPU())
results := make(chan uint64)
var current uint64
for i := 0; i < GOROUTINES; i++ {
go maxStart(current, current + PER_GOROUTINE, results)
current += PER_GOROUTINE
}
var maxStart uint64
for i := 0; i < GOROUTINES; i++ {
start := <-results
if start > maxStart {
maxStart = start
}
}
fmt.Println(maxStart)
}
Surely I am being stupid? Ideas? Thanks!
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.