Go and Pythagoras

yourbasic.org/golang

Pythagorean triples are integer solutions to the Pythagorean Theorem, a2 + b2 = c2.

A well-known example is (3, 4, 5):

fmt.Println(3^2+4^2 == 5^2) // true

The triple (6, 8, 10) is another example, but Go doesn't seem to agree.

fmt.Println(6^2+8^2 == 10^2) // false

Answer

The circumflex ^ denotes bitwise XOR in Go. The computation written in base 2 looks like this:

0011 ^ 0010 == 0001   (3^2 == 1)
0100 ^ 0010 == 0110   (4^2 == 6)
0101 ^ 0010 == 0111   (5^2 == 7)

Of course, 1 + 6 == 7; Go and Pythagoras agree on that. See Bitwise operators cheat sheet for more about bitwise calculations in Go.

To raise an integer to the power 2, use multiplication.

fmt.Println(6*6 + 8*8 == 10*10) // true

Go has no built-in support for integer power computations, but there is a math.Pow function for floating-point numbers.

Share this page: