Beginner - Having an issue with simple multiplication algorithm

agolangf · 2017-08-13 03:00:31 · 648 次点击    
这是一个分享于 2017-08-13 03:00:31 的资源,其中的信息可能已经有所发展或是发生改变。

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:

You want x % 2 != 0. If the number is even, you don't add it up.

Also: you can simplify y = y << 1 to y <<= 1 and z = z + y to z += 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.

Jumballaya:

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!


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

648 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传