Euler 9 in Go
For fun I picked one of the Euler algorithms I had played with before and
rewrote it in Go. Instead of carrying over the nested-loop search, this
version first eliminates c using the fixed sum and solves the Pythagorean
equation for b. Only a remains to search.
package main
import (
"fmt"
"os"
)
func main() {
const sum = 1000
for a := 1; a < sum/3; a++ {
numerator := sum * (sum - 2*a)
denominator := 2 * (sum - a)
if numerator%denominator != 0 {
continue
}
b := numerator / denominator
c := sum - a - b
if a < b && b < c {
fmt.Println(a * b * c)
return
}
}
fmt.Fprintln(os.Stderr, "no solution")
os.Exit(1)
}
The divisibility check rejects values of a that would produce a fractional
b. The program uses constant space, examines fewer than sum / 3 candidates,
and prints 31875000.