<p>Hello, I am learning Go and I started by recreating the simple 'Egyptian Multiplication Algorithm', also known as the 'Russian Peasants Algorithm' </p>
<p>my code:</p>
<pre><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))
}
</code></pre>
<p>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.</p>
<p>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?</p>
<hr/>**评论:**<br/><br/>mwholt: <pre><p>You want <code>x % 2 != 0</code>. If the number is even, you <em>don't</em> add it up.</p>
<p>Also: you can simplify <code>y = y << 1</code> to <code>y <<= 1</code> and <code>z = z + y</code> to <code>z += y</code>.</p>
<p>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.</p></pre>Jumballaya: <pre><blockquote>
<p>You want <code>x % 2 != 0</code>. If the number is even, you don't add it up.</p>
</blockquote>
<p>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.</p>
<p>Thank you for the shorthand too!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传