summaryrefslogtreecommitdiff
path: root/gcd.go
blob: 96f601b5b6615fca4a1f7f80e54607ae9aa68c9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 SYNOPSIS:

 With GCC >= 4.6:
 # gccgo gcd.go -o gcd-go
 # ./gcd-go 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

*/

package main

import (
	"fmt"
	"os"
	"strconv"
)

func gcd2(a, b uint64) uint64 {
	if b == 0 {
		return a
	}
	return gcd2(b, a%b)
}

func gcdn(ns []uint64) (r uint64) {
	for _, v := range ns {
		r = gcd2(r, v)
	}
	return
}

func main() {
	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))
}