14 Jun 2011 maragato   » (Master)

Euler 9 in Go

This was surprising to me. For fun I picked one of the Euler algorithms I played with in the past and rewrote it in Go. The idea was to rewrite it idiomatically to see how different things might look. Nothing else. The very first thing I did was to get the exact algorithm and rewrite, no idiomatic changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main
 
import "fmt"
 
func isTriplet(a, b, c int) bool {
        return a * a + b * b == c * c
}
 
func main() {
        for a := 1; a < 1000; a++ {
                for b := a + 1; b < (1000 - a) / 2; b++ {
                        c := 1000 - a - b
                        if isTriplet(a, b, c) {
                                fmt.Println(a * b * c)
                                return
                        }
                }
        }
 
}

What surprised me is that this thing runs in 0.005s, which is faster than the Python implementation and very close to the one in C. It surprised me because this wasn’t really supposed to happen. The Go compiler isn’t well optimized, especially compared to compilers with a many-years headstart.

Syndicated 2011-06-14 15:30:06 from Roberto Teixeira's blog

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!