# Beginner - Having an issue with simple multiplication algorithm

agolangf · · 15 次点击
<p>Hello, I am learning Go and I started by recreating the simple &#39;Egyptian Multiplication Algorithm&#39;, also known as the &#39;Russian Peasants Algorithm&#39; </p> <p>my code:</p> <pre><code>package main import &#34;fmt&#34; func russian_peasants_algorithm(x, y int) (z int) { for x &gt; 0 { if x % 2 == 0 { z = z + y } y = y &lt;&lt; 1 x = x &gt;&gt; 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&#39;t firing properly? I finished A Tour of Go and starting working on my local machine but can&#39;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&#39;t</em> add it up.</p> <p>Also: you can simplify <code>y = y &lt;&lt; 1</code> to <code>y &lt;&lt;= 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&#39;d use PHP or C or Python (for various reasons) as long as I can find a good package for what I&#39;m working with.</p></pre>Jumballaya: <pre><blockquote> <p>You want <code>x % 2 != 0</code>. If the number is even, you don&#39;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>
0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet