Finding a Common Breath in Numbers
A melody played by ear can be slippery to count. Suppose one harmonica phrase lasts 12 beats and an answering phrase lasts eight. I want to break both into equal groups without leaving a partial group at the end. Groups of four beats fit: three groups for the first phrase, two for the second.
That four is the greatest common divisor, and the Euclidean algorithm finds it by repeatedly taking a remainder. Euclid described the method around 300 BCE; it is still a neat piece of computing because each step replaces the original problem with a smaller one.
package main
import "fmt"
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
func main() {
fmt.Println(gcd(12, 8))
}
The first remainder is four. Then eight divided by four leaves no remainder, so four is the answer. The trick works because any number that divides both original lengths must also divide their remainder. Repeating that observation preserves the answer until there is nothing left to divide.
Lua tells the same story with a compact function:
local function gcd(a, b)
while b ~= 0 do
a, b = b, a % b
end
return a
end
print(gcd(12, 8))
Both programs print 4. They assume non-negative whole-number beat counts, with at least one count greater than zero. A group is a counting aid, not a command to breathe every four beats: phrasing and breath control still depend on the melody. For lengths of 12 and seven, the result is one, so whole beats are the largest equal groups that fit both. The arithmetic gives me a useful grid; my ears decide what to play on it.