Hello, I am learning Go and I started by recreating the simple 'Egyptian Multiplication Algorithm', also known as the 'Russian Peasants Algorithm'
my code:
package main
import "fmt"
func russian_peasants_algorithm(x, y int) (z int) {
for x > 0 {
if x % 2 == 0 {
z = z + y
}
y = y << 1
x = x >> 1
}
return
}
func main() {
fmt.Println(russian_peasants_algorithm(2, 3))
}
This is printing the number 3 instead of 6. It seems like the if statement isn't firing properly? I finished A Tour of Go and starting working on my local machine but can't figure out what the issue on this code is. I downloaded gore to use as a REPL and stepped through the code line by line and it seems to be doing what it needs to be.
Thank you in advance, I am also wondering what types of projects I can build to learn Go, where does Go really shine, and what type of programs are fun to build with Go?
评论:
mwholt:
Jumballaya:You want
x % 2 != 0
. If the number is even, you don't add it up.Also: you can simplify
y = y << 1
toy <<= 1
andz = z + y
toz += y
.Go is good for lots of things. I use it anywhere I'd use PHP or C or Python (for various reasons) as long as I can find a good package for what I'm working with.
You want
x % 2 != 0
. If the number is even, you don't add it up.Yep, holy crap. What a mistake!! I am in the middle of building a repo of alogrithms in a few different languages and I just threw Go in the mix and I guess I decided to mess up that line.. It figures that it would be such a small mistake.
Thank you for the shorthand too!
