summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIgor Pashev <pashev.igor@gmail.com>2012-03-30 23:54:57 -0700
committerIgor Pashev <pashev.igor@gmail.com>2012-03-30 23:54:57 -0700
commit015f5e16a135b7210909cf0fd4ca70e92ecf9171 (patch)
tree26f803581975c7ce4535844becd84abbb94cc7cc
parent5782cfb5d6705a2ab70a9f950bfca3d4d81c16e4 (diff)
parent63c82ffa82536cda16370e80bed7f6e502cdfd36 (diff)
downloadgcd-015f5e16a135b7210909cf0fd4ca70e92ecf9171.tar.gz
Merge pull request #1 from krasin/master
Update gcd.go to Go 1. Make the code more idiomatic
-rw-r--r--gcd.go71
1 files changed, 31 insertions, 40 deletions
diff --git a/gcd.go b/gcd.go
index 04f772d..96f601b 100644
--- a/gcd.go
+++ b/gcd.go
@@ -5,10 +5,11 @@
# gccgo gcd.go -o gcd-go
# ./gcd-go 11 22 33 44 121
- With Google Go (6g for amd64, 8g for x86, http://golang.org/cmd/):
- # 6g -o gcd-go.o gcd.go
- # 6l -o gcd-go-6g gcd-go.o
- # ./gcd-go-6g 11 22 33 44 121
+ With Google Go (http://golang.org/):
+ # go run gcd.go 11 22 33 44 121
+ # or, if you want to play with the binary
+ # go build -o gcd-go gcd.go
+ # ./gcd-go 11 22 33 44 121
GCC makes dynamically linked binary,
but Google Go - statically linked
@@ -17,45 +18,35 @@
package main
-// Both Google Go and GCC issue an error "imported and not used",
-// if imported and not used :-)
-import "fmt"
-import "flag"
-import "strconv"
-
-func gcd2 (a, b uint) uint {
- if b == 0 {
- return a
- }
- /* 6g issues an error "function ends without a return statement",
- if we use if ... {... return} else {... return}.
- But GCC doesn't.
- */
- return gcd2(b, a % b)
+import (
+ "fmt"
+ "os"
+ "strconv"
+)
+
+func gcd2(a, b uint64) uint64 {
+ if b == 0 {
+ return a
+ }
+ return gcd2(b, a%b)
}
-func gcdn (ns []uint) uint {
- var r uint // zero by default
- for i := range ns {
- r = gcd2(r, ns[i])
- }
- return r
+func gcdn(ns []uint64) (r uint64) {
+ for _, v := range ns {
+ r = gcd2(r, v)
+ }
+ return
}
func main() {
- flag.Parse() // without this 6g will give flag.NArg() = 0 next (WTF?)
- n := flag.NArg()
- if n > 0 {
- ns := make([]uint, n) // We have garbage collector!
-
- // Or: for i := range ns, since range of ns is equal to flag.NArg()
- for i := 0; i < n; i++ {
- // Drop the second return value (error code):
- ns[i], _ = strconv.Atoui(flag.Arg(i))
- }
-
- g := gcdn(ns)
- fmt.Printf("%v\n", g)
- }
+ if len(os.Args) == 1 {
+ return
+ }
+ var ns []uint64 // We have garbage collector!
+ for _, arg := range os.Args[1:] {
+ // Drop the second return value (error code):
+ v, _ := strconv.ParseUint(arg, 0, 64)
+ ns = append(ns, v)
+ }
+ fmt.Printf("%v\n", gcdn(ns))
}
-